Skip to main content

Using Svelte in ActiveJ projects

We have already looked at how you can use ActiveJ framework in combination with React here. In this example we will integrate Svelte in an ActiveJ project. You can find full example sources on GitHub. Here we will consider using HttpServerLauncher and AsyncServlet to set up the server that processes the requests. See how ActiveJ makes this process extremely simple.

Creating launcher

SvelteApplicationLauncher extends HttpServerLauncher. HttpServerLauncher superclass takes care of setting up all the required configurations for the HTTP server:

public final class SvelteApplicationLauncher extends HttpServerLauncher {  @Provides  Executor executor() {    return newSingleThreadExecutor();  }
  @Provides  AsyncServlet servlet(Executor executor) {    return StaticServlet.ofClassPath(executor, "public")        .withIndexHtml();  }
  public static void main(String[] args) throws Exception {    SvelteApplicationLauncher launcher = new SvelteApplicationLauncher();    launcher.launch(args);  }}

First, we provide an executor for the AsyncServlet. Then, we provide an AsyncServlet which is actually a StaticServlet that serves th index.html as well as bundle.js from the provided path (/public). Finally, we write down main() method to launch SvelteApplicationLauncher.

Building Svelte project

We used a code from a basic "Hello world" Svelte Tutorial. The code is located inside the /front directory. To build a Svelte project you need to execute the following commands from within the /front directory:

npm inpm run build

All the built files are then copied to the Java's src/main/resources directory to be served by the server. This happens thanks to the custom prebuild and postbuild scripts in package.json file.

Running the application

If you want to run the example, clone ActiveJ:

git clone -b examples-5.3 https://github.com/activej/activej.git

After that, open the project in your IDE of choice. Then navigate to the examples/tutorials/svelte-integration/front directory and execute npm-commands as described previously. Make sure that there is now a src/main/resources/public directory with Svelte-built files.

Before running the example, build the project (Ctrl + F9 for IntelliJ IDEA). Open SvelteApplicationLauncher class and run its main() method. Then open your favourite browser and go to localhost:8080