4

Hey i feel a bit dub to ask this question, but i don't seem to find the answer online:

I currently have a nodejs express Server, that renders my views as follows:

router.get('/example',ensureAuthenticated, function (req, res) {
  res.render('ejs_view', {
     title:"Title",
     msg:req.flash('msg'),
     err:req.flash('error'),
     user:req.user
  });
});

Now i wan to integrate Svelte, but keep some ejs templates for the beginning:

How can i use Express as Router for Svelte views?

Paul
  • 89
  • 1
  • 7
  • Maybe you can mix this two things : [consolidate view engine](https://stackoverflow.com/questions/15063262/is-there-any-way-to-use-multiple-view-engines-with-express-node-js) with [svelte template engine](https://www.npmjs.com/package/svelte-view-engine) – BENARD Patrick Jan 07 '20 at 11:04
  • @PimentoWeb it looks like consolidate.js does not support Svelte yet, but i will give it a try; Thanks – Paul Jan 07 '20 at 11:49

1 Answers1

1

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
Bugbit
  • 41
  • 1