Search code examples
javascriptnode.jsecmascript-6project-structure

Node.js: What is the proper way of splitting code?


My index.js file has a lot of code which could be split into many pieces.

Basically it looks something like this:

importing many dependencies;
importing many custom functions;

defining constants;

setting up express;
setting up apollo-server;

post-request #1
get-request #1
requests....

app.listern on port

I want my index.js file to contain only imports

To do so I've split my code into many .js files. The majority of files doesn't export anything, but represented as a piece of code like my this:

// it's a listen.js file
db.sequelize.sync().then(function() {
  app.listen(process.env.PORT || 3000);
});

I import it like this using es6 syntax (I import the whole file):

import './core/api/rest/listen'

and get an error:

db is not defined

I understand why it's not defined in listen.js, because I did not imported it into listen.js, but I imported db in my index.js before I importing listen.js. Why doesn't it visible?

BTW, db here is just one of many variables that raises an error.

Correct me if I'm wrong, but I think that if I import all my variables/constants/dependencies in index.js all these variables become accessible to imported files


Solution

  • The import statement is used to import bindings which are exported by another module.

    Please see more: developer.mozilla.org/.../Statements/import

    You need to export the class/ functions/ variables you want to import