I have an express app that follows the standard Express 4 format. ie, dependencies at the top, then app config, then routes, and finally, listen.
I'm trying to seperate out my routes into categorised files (eg. routes/authentication.js) however the app isn't carrying through the dependencies so when I run node app.js
the app breaks because the CLI says that passport isn't defined in routes/authentication.js, which it isn't, because it's defined at the top of app.js with all the other dependencies.
I guess my question is how can I go about 'sharing' the dependencies so I don't have to list them at the top of every file? This is how i'm requiring the separate files:
app.js
require('./app/routes/authentication')(app);
routes/authentication.js
module.exports = function (app) {
[routes]
}
Where a dependency module is really used often where you already have access to app, you can set the value on app, eg app.config = require('./config')
. ( However , where it is generally best to specify the dependencies for a particular module at the top of that module for the sake of clarity. There's no harm other than adding a bit more code for each module.)
Additionally, although it is fine to use a constructor function and passing in app
to this function, you could also use modules for this purpose. Ensure you export app
the moment you create it, ie var app = module.exports = express();
and then just var app = require('../app');
from other libraries. You'll see this in some of the Express examples.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.