What is the best way to bring in extra files to server.js while working with sapper?

When working on my sapper app, I attempted to import a file into the server.js file using the following code:

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);
    });

Unfortunately, I keep encountering the following error in the console:

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

The structure of my root folder is as follows:

 - src
   - backend
     - controllers
       - push.js

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

I am utilizing sapper with the default rollup configuration. Is it possible that the error is related to rollup? How can I go about resolving this issue?

Answer №1

After conducting a brief test, it appears that your structure is functioning properly. Just ensure you have the following:

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

Additionally, remember to utilize import instead of require:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alert: npm indicates an absence or outdated status of a package

After running npm install, I encountered the following warnings: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8de5ecffa0fbece1e4e9ecf9e2ffcdb8a3bca3b8">[email protected]</a>: this library is ...

express.static() fails to serve files from public directories when accessed via router paths other than "/"

Express static configuration: app.use(express.static(__dirname + "/public")); Directory Structure: --public --assets --js --[JavaScript scripts] --stylesheets --[CSS files] Defined Routes: const shopRoutes = require('./routes/shopRo ...

Is there a way to differentiate between a browser application running on a local development server and an online staging server?

Is there a way to conditionally call a component only on the staging server and not on the local machine in Vue.js? <save-drafts-timer v-if="!environment === 'development'" /> ... data () { return { environment ...

Executing programmatic action calls in ActionHero.js

This is my first time using ActionHero and I have a specific requirement. I need to add an item to the queue, wait until it has finished processing and retrieve the resulting data. Afterwards, I need to proceed with another item in the queue before respond ...

Webpack fails to transmit watchOptions to the watcher

Having an issue with webpack and wondering if fixing it will require forking the repo. Also, seeking guidance on merging it back in. The problem arises when using the webpack npm module environment in a development virtual machine where code is edited on ...

Having trouble with running `npm start` on a computer that has different versions of Node and

I have encountered an issue with running a React application on two different computers. One computer, a MacBook, is running the app without any problems, while the other, an Ubuntu 18.04 machine, is having trouble starting it. Here are the configurations ...

The asynchronous method in a Mongoose schema does not pause for completion

Here is the code snippet that I am currently working on: const user = await User.findOne({ email }).select('+password'); console.log(' user value : ', user); const boolean = await user.comparePassword(password, user.password); console.l ...

Issue with Node.js: npm is failing to install now

I'm facing an issue while trying to install a module using npm as it keeps returning errors. Even when attempting to install the same module, like in this example: npm install socket.io The following error is shown: npm ERR! TypeError: Cannot call ...

The function Amplify.configure does not exist

Currently attempting to utilize AWS Amplify with S3 Storage, following the steps outlined in this tutorial for manual setup. I have created a file named amplify-test.js, and here is its content: // import Amplify from 'aws-amplify'; var Amplify ...

Having trouble removing global npm packages following nvm installation

I've come across several discussions regarding this problem, but none seem to address my specific case and I have not been successful in resolving it by following the suggestions I found. After executing npm uninstall -g "some package" it simply dis ...

Populating a many-to-many relationship in Mongoose using uni-directional references

These are the schemas I'm using to represent a many-to-many relationship: var GenreSchema = new Schema({ name: {type: String}, }); mongoose.model('Genre', GenreSchema); var MovieSchema = new Schema({ title: {type: String}, genres ...

Transfer image using ASIHttpRequest. iOS app / node.js backend

When uploading a picture on the client side, I am using ASIHttpRequest: // Code for uploading to server NSLog(@"Upload to server"); UIImage *im = [UIImage imageNamed:@"ok.png"]; NSData *da = UIImageJPEGRepresentation(im, 0.6); NSLog(@"DATA:%@", da); NSSt ...

I'm having trouble with getting npm start to function properly. I've exhausted all my options and I'm feeling lost

Every time I execute npm start in my React project, an error pops up: [email protected] start C:\Users\AyaLe\Desktop\React\myapp react-scripts start It seems there might be a problem with the project's dependency tre ...

Tips for transferring environment variables from a file to a node command

After installing a command via npm (db-migrate), I wanted to automate database migration by running it from the command line. The script's config file allows for referencing environment variables, which is useful as I have already set database credent ...

Tips on transitioning a Node.js application from JavaScript to TypeScript incrementally

I have a JavaScript node application that has grown quite large and I am considering migrating to TypeScript for faster development and easier code maintenance. I have installed TypeScript along with the node and mocha types using the following commands: ...

Encountering a NPM Error while trying to install packages for a fresh project

Yesterday everything was working perfectly fine with installing packages from a project, but today I encountered an error. I attempted to install packages from another project and it seems to work without any issues. I haven't made any changes from ye ...

Exploring the Dynamics between Koa, Co, Bluebird, Q, Generators, Promises, and Thunks in Node.js

Exploring the development of a web application using Koa has left me with questions about when and why to choose between various "making async easier" technologies. The abundance of online information on this topic has not provided clear guidance, especial ...

Utilizing Node.js: Chaining process.exit() functions

Is there a way to chain process.on('exit') calls in JavaScript? process.on('exit', function firstHandler(err,code,cb){ //this signature is fictitious for this example only if(condition){ cb(null); // this would call the ...

Tips for Angular JS Single Page Applications: Implementing Angular Controllers to Invoke Angular Services

Currently, I'm in the process of building a Node.js Application using Angular.js and Express.js. My goal right now is to populate a list with customer names and addresses by using this code snippet: var mylist = new generic.list(); mylist.add({name ...

Are you ensuring compliance with licensing in your Webpack bundles?

Can webpack be used to verify license compliance? I'm looking for a way to ensure that the license headers from all modules built by webpack are included in the final output file. How can we confirm this is happening? Furthermore, I am also intereste ...