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
:
$ npm run build
> svelte-app@1.0.0 build /school-lunch/frontend
> npx eslint ./src && vite
src/main.js → public/build/bundle.js
created public/build/bundle.js in 5.6s
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:
$ tree
.
├── build
│ ├── bundle.css
│ ├── bundle.css.map
│ ├── bundle.js
│ └── bundle.js.map
└── index.html
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:
Delete the existing boilerplate files in the Express
/backend/public
directoryRun
npm run build
from the Svelte frontend directoryCopy the files from the Svelte
/frontend/public
directory to/backend/public
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