Search code examples
node.jscommonjsrollupsapper

How can i import additional files into server.js using sapper?


In my sapper app, i try to import a file into the server.js file like this:

import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';

const pushController = require('./backend/controllers/push');

polka()
    .use(
        compression({ threshold: 0 }),
        sirv('static', { dev }),
        sapper.middleware()
    )
    .post('/something/route', pushController.subscribe)
    .listen(PORT, err => {
        if (err) console.log('error', err);
    });

But i always get the Error on console:

Error: Cannot find module './backend/controllers/push

my root folder looks like this:

 - src
   - backend
     - controllers
       - push.js

   - client.js
   - server.js
   - service-worker.js
   - template.html

I am using sapper with the default rollup config. Could the error therefore be related to rollup? How can I fix it?


Solution

  • A quick test shows it's ok with your structure. Please make sure you have

    # push.js
    function pushController() {
      ...
    }
    ...
    module.exports = { pushController }
    

    and use import instead of require

    # server.js
    import { pushController } from './backend/controllers/push'