简体   繁体   English

是否需要一次文件并使用 function 参数传输它,还是每次在文件中都需要它?

[英]Is it better to require a file once and transfer it with a function parameter or to require it each time in the file?

Which situation is the most efficiency?哪种情况效率最高?
file1.js

// Situation 1
const lang = require(`path/to/file/${value}`);
file2.run({ lang });
// Situation 2
const lang = value;
file2.run({ lang });

file2.js

// Situation 1
exports.run = runArgs => {
    const { lang } = runArgs;
    // lang has already the wanted value.
};
// Situation 2
exports.run = runArgs => {
    const { lang } = runArgs;
    const language = require(`path/to/file/${lang}`);
};

After a file got "required" once, Node caches it, all the other "requires" (from other files) will use the same cached value, so you should keep it simple and require the module from all the files that need it.在一个文件被“需要”一次后,Node 缓存它,所有其他“需要”(来自其他文件)将使用相同的缓存值,所以你应该保持简单,并从所有需要它的文件中请求模块。

You can read more about it here and here您可以在此处此处阅读有关它的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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