node.js中的require()与module.require()?

时间:2018-09-20 12:13:03

标签: node.js npm module

nodejs中的 require() module.require()有什么区别?

文档没有提供任何关于它们之间区别的内容。谁能解释?

3 个答案:

答案 0 :(得分:0)

官方文档不仅不清楚它们之间的区别,而且缺少任何示例用法,这些用法将有助于确定使用module.require和require的有用性。因此,我进行了实验,发现实际上,require()采取了相对于模块进行导入的路径,其中module.require采取了模块ID(在文档中进行了概述,但这是一个几乎不清楚“ id”指的是什么。)

因此,id实际上是指模块对象(module.id)的属性“ id”。如果从模块内进行console.log(module.id),则将获得该文件的完整路径。但是,使用module.require()加载模块的唯一方法是可以访问module.id变量,该变量不会在module.exports中导出。因此从技术上讲,您可以这样将当前模块加载到内部:

示例用法1:

test.js

module.exports = {};
module.exports.foo = function() {
    console.log('bar');
};

let thisModule = module.require(module.id);
thisModule.foo();

app.js

const test = require('./test');

输出

$ bar

这个用例如何有用还不是我的主意,但是出于某些原因,可以在其内部加载模块以运行其自己的导出功能。另一个可能的用例是这样的:

用法示例2:

test.js

const loader = require('./loader');    // Some library that handles module loading
                                       // dynamically. loader.register passes the module
                                       // info to the dynamic loader to be called
                                       // later by the client perhaps.
loader.register(module);

module.exports = {};
module.exports.foo = function() {
    console.log('bar');
};

app.js

const loader = require('./loader');
const test = loader.require('./test');    // loader module will have to do some parsing
                                          // to match './test' with the fully qualified
                                          // path name. Just to be clear, loader.require
                                          // is some function defined by the library
test.foo();

理论上输出条。因此,如果您出于某种原因要控制模块的加载,我想第二个用例可能会很有用。但是您必须专门针对此用法构建模块。我想可能还有其他用途,我打算做进一步调查,如果发现任何新发现,我将扩大这个答案。希望对您有所帮助。

答案 1 :(得分:-1)

module.require的文档很明确:

module.require方法提供了一种加载模块的方式,就像从原始模块中调用了require()一样。 为此,必须获取对模块对象的引用。由于 require()返回module.exports ,并且模块通常仅在特定模块的代码内可用,因此必须显式导出它才能使用

答案 2 :(得分:-1)

它们都需要其他模块(调用其他模块并返回其module.exports对象)

module.require('./module1.js');
require('./module1.js');

但它们不相同

require === module.require      // -> false 

module.require仅可用作方法
require是一种方法,但也有自己的属性(cache main)  提供其他数据

module.require.cache           // -> undefined 
require.cache                  // -> {the cached module}  
相关问题