简体   繁体   中英

is passing app = express() into another module the same as requiring the module?

I am wondering what is the difference between passing app = express() into another module versus requiring express within that module instead.

if I was to pass app = express() like so:

var app = require('express');
app.locals.title = title;
require('somemodule')(app);

then in the somemodule;

exports = function(app) {
    console.log(app.locals.title);
}

would you be able to use the app.locals variable set in the core file if you was to require express again within another module like so instead.

var app = require(express);
console.log(app.locals.title);

if not would you have to redefine the app.locals within this module?

which method would be best to use.

First, I'll assume you're using Express 4x. In 4x, the module actually exports a function, so you'll need to first create the app, after requiring the module. Like so:

var express = require('express');
var app = express();

If the module does something like adding middleware, or adding functionality to the app you create in your project, then it's only going to work if you first create the app, then pass it into the module. See below:

var express = require('express);
var app = express();
require('middleware-adder')(app);
// app now has the middeware provided by my module.

Anything set on the app before passing it into the module you're requiring (like app.locals.title in your example), would indeed be accessible inside of the module. As the author of a module, you'll need to be extra certain that the consumers are passing what you expect them to be though!

Hope this helps.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM