gpt4 book ai didi

javascript - 操作 module.exports 和 require

转载 作者:行者123 更新时间:2023-12-03 02:24:33 24 4
gpt4 key购买 nike

有一件事我不太理解 module.exports 和 NodeJS 的 require() 。由于我无法正确解释,因此找不到我要查找的信息,因此我来这里寻求一些帮助来寻找答案。

我可以导出如下函数:

example1.js

module.exports = {
hello: function() {
return 'Hello world';
});
}

或者

example2.js

module.exports = function(data) {
return data;
}

我可以将它与类似的东西一起使用:

console.log(require('./example1.js').hello());

或者

console.log(require('./example2.js')('hello world'));

从那里开始,如果我在 server.js 中调用 NPM 模块,如下所示:var bcrypt = require('bcrypt'); 并且我想在另一个模块中使用它,最好将它传递给如下函数:

example3.js

module.exports = function(bcrypt) {
return bcrypt.hashSync('hello', 5);
}

之后(记录哈希值):

console.log(require(./example3.js)(bcrypt));

或者直接在模块中声明它?

example3bis.js

var bcrypt = require('bcrypt');
module.exports = function() {
return bcrypt.hashSync('hello', 5);
}

另一个问题,如果我在 server.jsexample3bis.js 等特定模块中声明 bcrypt,是否意味着我在复制代码?

最后,模块是否有可遵循的良好实践?

我不知道我是否清楚地解释了事情,但我尝试理解模块(npm 或导出)周围的事情,以及如果多次调用代码,代码是如何重复的。

预先感谢您的回答!

最佳答案

好的,这就是答案

  1. require 文件中正在使用该模块的模块,不要传递它。

  2. require 只是维护已加载模块的缓存,因此多次 require 模块不会有任何性能损失,并且没有代码也有重复

所以一般来说,根本不需要担心代码重复或性能问题,这些已经在模块系统中考虑到了,只需在需要它的文件中需要模块,而不是作为参数传递,这会导致更干净的代码

关于javascript - 操作 module.exports 和 require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49006599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com