Я прошел некоторые тесты, и я думаю, что это может пролить свет на предмет ...
app.js
:
var ...
, routes = require('./routes')
...;
...
console.log('@routes', routes);
...
версии /routes/index.js
:
exports = function fn(){}; // outputs "@routes {}"
exports.fn = function fn(){}; // outputs "@routes { fn: [Function: fn] }"
module.exports = function fn(){}; // outputs "@routes function fn(){}"
module.exports.fn = function fn(){}; // outputs "@routes { fn: [Function: fn] }"
Я даже добавил новые файлы:
./routes/index.js
:
module.exports = require('./not-index.js');
module.exports = require('./user.js');
./routes/not-index.js
:
exports = function fn(){};
./routes/user.js
:
exports = function user(){};
Получаем вывод «@routes {}»
./routes/index.js
:
module.exports.fn = require('./not-index.js');
module.exports.user = require('./user.js');
./routes/not-index.js
:
exports = function fn(){};
./routes/user.js
:
exports = function user(){};
Получаем вывод «@routes {fn: {}, user: {}}"
< hr> ./routes/index.js
:
module.exports.fn = require('./not-index.js');
module.exports.user = require('./user.js');
./routes/not-index.js
:
exports.fn = function fn(){};
./routes/user.js
:
exports.user = function user(){};
Получаем output "@routes {user: [Function: user]}« Если мы изменим user.js
на { ThisLoadedLast: [Function: ThisLoadedLast] }
, мы получим вывод «@routes {ThisLoadedLast: [Function: ThisLoadedLast]}».
Но если мы изменим ./routes/index.js
...
./routes/index.js
:
module.exports.fn = require('./not-index.js');
module.exports.ThisLoadedLast = require('./user.js');
./routes/not-index.js
:
exports.fn = function fn(){};
./routes/user.js
:
exports.ThisLoadedLast = function ThisLoadedLast(){};
... мы получаем «@routes {fn: {fn: [Function: fn]}, ThisLoadedLast: {ThisLoadedLast: [Function: ThisLoadedLast]}}"
Поэтому я предлагаю всегда использовать module.exports
в определениях вашего модуля.
Я не полностью и вы можете понять, что происходит внутри с узлом, но, пожалуйста, прокомментируйте, если вы можете больше понять это, поскольку я уверен, что это помогает.
- Счастливое кодирование