This video is available to students only

Building and Serving Svelte

Building and Serving a Svelte App

Building a Svelte App#

Up until now, we have been running our Svelte app using the local Svelte dev server on port 5000. As web browsers cannot run .svelte files directly, the Svelte framework converts Svelte files into a single JavaScript file called bundle.js. It also creates a single CSS file called bundle.css.

In the local dev environment, Svelte automatically runs a new build after file changes and hot-loads that new build into the browser. This great for development, but not production.

In order to build a Svelte app for production, we run the command npm run build:

The output from the command says "created public/build/bundle.js". Run this command and take a look at /public, you'll see the following files:

There's an index.html file and CSS and JavaScript files. This is your whole Svelte application, ready to be deployed to a web server. These files are known as static assets and can be served from any web server.

Serving Static Assets from Express#

One web server option for our application is to use our backend Express server to host both the API portion of the app and serve the static Svelte portion of the app. The setup for this option is pretty easy. We just need to copy the files from /frontend/public into /backend/public.

Do the following:

  1. Delete the existing boilerplate files in the Express /backend/public directory

  2. Run npm run build from the Svelte frontend directory

  3. Copy the files from the Svelte /frontend/public directory to /backend/public

  4. Run the backend with npm run nodemon

When you start up the backend with nodemon, you'll probably see a bunch of eslint errors. Add "ignorePatterns": [ "public/*" ], to the .eslintrc.json file to ignore the public directory:

 

This page is a preview of Fullstack Svelte

Start a new discussion. All notification go to the author.