If you grab one of the Svelte/Sapper templates,
i.e. npx degit "sveltejs/sapper-template#rollup" my-app
you will get routing managed by a package called Polka.
This can easily be replaced to use Express by installing express and changing the line polka() // You can also use Express
(you must import express instead of polka at the top).
I've been trying to find out how to integrate an existing Express app with Svelte/Sapper - I've had the most success from copying the structure from here:
https://github.com/appshore/SvelteSapperGraphQL
If you clone that repo, you'll see there's a server folder in src > routes with the express routing.
The Express options that would usually be defined in a root app.js file are put into src > server.js.
The way I've done it is all routes are rendered by Sapper unless they are defined in server.js (which for me is only POST/GET requests, but I'm sure would be fine to render EJS views as well).
My server.js file:
import sirv from 'sirv';
import express from 'express';
// import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';
import routes from './server/routes';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// '/api' acts as a trigger route to use pure Express and ignore Sapper
app.use('/api', routes)
// polka() // You can also use Express
app.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
// Set public folder
app.use(express.static('static'))
Folder structure:
Template Sapper app:
- src
- server.js // Express options here
- server
- routes.js // Express routes here (used under '/api' route)
- .. folders with each route
- routes // Sapper routes
- static
- __sapper__
- .. other sapper files