有没有办法在nodejs中加载特定模块?
Is there a way to load specific modules in nodejs?
我正在使用 NodeJS 创建一个应用程序,我想只导入我自己的模块的某些部分,这样我可以稍后加载其他部分(这是为了提高性能,而不必加载我的所有模块记忆)。例如:
test.js
const foo = () => {
//something
return x
}
const bar = () => {
//something
return y
}
module.exports.someFunc = foo
module.exports.otherFunc = bar
所以,如果我像这样导入 app.js:
app.js
const a = require('./test').someFunc
节点是否正在从 test.js 加载 someFunc?或者,它是否加载了缓存中的两个函数的整个脚本?
我用谷歌搜索了很多,但找不到合适的答案。
Is node just loading someFunc from test.js? Or, does it load the whole script with both of the functions in the cache?
后者。如果模块尚未加载,则加载并执行其完整文件(具有所有副作用),并缓存生成的导出对象。然后你得到一个模块的导出对象的引用,然后 你的 代码从中获取 someFunc
。
这是 Node 模块系统的当前限制。如果您希望将它们分开,则需要将它们分开(然后可能创建一个模块,其工作是加载它们,对于已经使用完整模块的代码),例如:
foo.js
:
const foo = () => {
//something
return x
};
exports = foo;
bar.js
:
const bar = () => {
//something
return y
};
exports = bar;
..然后也许 test.js
:
const foo = require("./foo.js");
const bar = require("./bar.js");
module.exports.someFunc = foo;
module.exports.otherFunc = bar;
我正在使用 NodeJS 创建一个应用程序,我想只导入我自己的模块的某些部分,这样我可以稍后加载其他部分(这是为了提高性能,而不必加载我的所有模块记忆)。例如:
test.js
const foo = () => {
//something
return x
}
const bar = () => {
//something
return y
}
module.exports.someFunc = foo
module.exports.otherFunc = bar
所以,如果我像这样导入 app.js:
app.js
const a = require('./test').someFunc
节点是否正在从 test.js 加载 someFunc?或者,它是否加载了缓存中的两个函数的整个脚本?
我用谷歌搜索了很多,但找不到合适的答案。
Is node just loading someFunc from test.js? Or, does it load the whole script with both of the functions in the cache?
后者。如果模块尚未加载,则加载并执行其完整文件(具有所有副作用),并缓存生成的导出对象。然后你得到一个模块的导出对象的引用,然后 你的 代码从中获取 someFunc
。
这是 Node 模块系统的当前限制。如果您希望将它们分开,则需要将它们分开(然后可能创建一个模块,其工作是加载它们,对于已经使用完整模块的代码),例如:
foo.js
:
const foo = () => {
//something
return x
};
exports = foo;
bar.js
:
const bar = () => {
//something
return y
};
exports = bar;
..然后也许 test.js
:
const foo = require("./foo.js");
const bar = require("./bar.js");
module.exports.someFunc = foo;
module.exports.otherFunc = bar;