1

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

11
  • are you using babel in node.js? because node.js not support import yet... if not please use require. Commented Dec 5, 2017 at 17:44
  • @Ofear Yes, I do use it, I guess using require would not be an answer to my question Commented Dec 5, 2017 at 17:45
  • And where are you declaring on db? I don't see any declaration of variable named db Commented Dec 5, 2017 at 17:45
  • @Ofear, it's declared in a separate file and exported as a constant. It's imported before I import listen.js Commented Dec 5, 2017 at 17:47
  • try using import {*} from './core/api/rest/listen' <- this is not the best practice to use *.... btw.. are you exporting all those variables? can we see a glimpse of this file? ./core/api/rest/listen Commented Dec 5, 2017 at 17:52

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.