Node.js module.exports的用途是什么,如何使用它?

JavaScript

小小Eva

2020-03-09

Node.js module.exports的用途是什么,如何使用它?

我似乎找不到任何相关信息,但是正如我在源代码中经常看到的那样,它似乎是Node.js的重要组成部分。

根据Node.js文档

模组

对当前的引用 module特别module.exports 是与导出对象相同。请参阅 src/node.js以获取更多信息。

但这并没有真正的帮助。

究竟是module.exports做什么的,一个简单的例子是什么?

第265篇《Node.js module.exports的用途是什么,如何使用它?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
斯丁阳光 2020.03.09
let test = function() {
    return "Hello world"
};
exports.test = test;
理查德飞云 2020.03.09

模块将相关代码封装到单个代码单元中。创建模块时,这可以解释为将所有相关功能移动到文件中。

假设有一个文件Hello.js,其中包含两个函数

sayHelloInEnglish = function() {
  return "Hello";
};
sayHelloInSpanish = function() {
  return "Hola";
};

我们仅在代码的效用超过一个调用时才编写函数。

假设我们想将该功能的实用性增加到另一个文件,例如World.js,在这种情况下,导出文件就可以通过module.exports获取。

您可以通过下面给出的代码导出两个函数

var anyVariable={
 sayHelloInEnglish = function() {
      return "Hello";
    };
  sayHelloInSpanish = function() {
      return "Hola";
    }; 
}
module.export=anyVariable;

现在,您只需要在World.js中输入文件名即可使用这些功能

var world= require("./hello.js");
神无 2020.03.09

将程序代码划分为多个文件时,module.exports用于将变量和函数发布给模块的使用者。require()源文件中调用将替换为module.exports从模块中加载的相应文件

在编写模块时记住

  • 模块加载被缓存,只有初始调用评估JavaScript。
  • 可以在模块内使用局部变量和函数,而不需要导出所有内容。
  • module.exports对象也可用作exports速记。但是,当返回唯一函数时,请始终使用module.exports

模块出口图

根据:“模块第2部分-编写模块”

前端飞云 2020.03.09

如果您将对新对象的引用分配给exports和/或,则必须注意一些事项modules.exports

1.以前附加到原始属性的所有属性/方法,exports或者module.exports当然会丢失,因为导出的对象现在将引用另一个新属性/方法

这很明显,但是如果您在现有模块的开头添加导出的方法,请确保本机导出的对象在末尾没有引用另一个对象

exports.method1 = function () {}; // exposed to the original exported object
exports.method2 = function () {}; // exposed to the original exported object

module.exports.method3 = function () {}; // exposed with method1 & method2

var otherAPI = {
    // some properties and/or methods
}

exports = otherAPI; // replace the original API (works also with module.exports)

2.如果一个exportsmodule.exports引用一个新值,则它们不再引用同一对象

exports = function AConstructor() {}; // override the original exported object
exports.method2 = function () {}; // exposed to the new exported object

// method added to the original exports object which not exposed any more
module.exports.method3 = function () {}; 

3.棘手的结果。如果您同时更改对exports的引用module.exports,则很难说公开了哪个API(看起来很成功module.exports)。

// override the original exported object
module.exports = function AConstructor() {};

// try to override the original exported object
// but module.exports will be exposed instead
exports = function AnotherConstructor() {}; 
Mandy古一 2020.03.09

the module.exports property or the exports object allows a module to select what should be shared with the application

在此处输入图片说明

I have a video on module_export available here

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android