示例代码请访问我的 GitHub: https://github.com/chencl1986/nodejs-tutorial
Node.JS 定义模块
Node.JS 的模块化由于出现的较早, 因此它遵循的是 CommonJS 规范, 而非 ES6 的模块化.
在 Node.JS 的模块化中, 最常用到的有 module 对象, exports 对象, require 方法.
其中 module 和 exports 用于输出模块, require 用于引用模块.
一个简单的模块例子
示例代码:/lesson10/module1.JS,/lesson10/require.JS
先新建一个 module1.JS 文件, 代码如下:
- module.exports.a = 1
- module.exports.b = 2
- let c = 3
在 require.JS 中, 引入模块并打印:
- const module1 = require('./module1')
- console.log(module1)
可以看到打印结果:{ a: 1, b: 2 }.
这段代码的含义如下:
module1.JS 对外输出了 module.exports,module.exports 为一个对象, 它含有 a 和 b 属性.
module1.JS 中虽然定义了变量 c, 但它只在 module1.JS 这个模块中存在, 从外部无法访问.
在 require.JS 中引用 module1.JS, 必须使用相对路径或绝对路径.
若引用时不带路径, 而是直接使用模块名称, 则会默认引用项目目录下的 node_modules 文件夹下的模块, 如:
- const module2 = require('module2')
- console.log(module2) // {
- a: 1, b: 2
- }
若此时项目目录下的 node_modules 文件夹下存在 module2.JS 文件, 则会引用该文件.
若不存在, 则会查找系统的 node_modules 文件夹下, 即全局安装的模块, 是否存在 module2.
若还不存在该模块, 则会报错.
通过 require 导入的模块, 可以被任意命名, 因此写成 const a = require('module2') 也是可以的.
module.exports
上面这个例子中的模块导出, 还可以省略 module, 直接写成 exports.a = 1; exports.b = 1; ....
但直接使用 exports 导出, 也仅支持这种写法, 若写成:
- exports = {
- a: 1,
- b: 2
- }
在引用模块时, 只能接收到 {}, 也就是说 exports 只支持 exports.a = 1; 这样的语法.
如果要将整个模块直接定义为一个对象, 函数, 变量, 类, 则需要使用 module.exports = 123.
如下:
示例代码:/lesson10/module3.JS
- module.exports = {
- a: 1,
- b: 2
- }
- module.exports = 123
- module.exports = {
- a: 1,
- b: 2,
- c: 3
- }
- module.exports = function () {
- console.log('test')
- }
- module.exports = class {
- constructor(name) {
- this.name = name
- }
- show() {
- console.log(`Show ${this.name}`)
- }
- }
module.exports 可以让模块被赋值成任意类型, 但需要注意的是此时 module.exports 类似于一个模块内的全局变量.
对它的重复赋值, 只有最后的值有效, 之前的值会直接被覆盖.
在这个例子中, module3.JS 模块最终导出为一个类.
因此, 通常推荐使用 module.exports, 可以避免出错.
来源: https://juejin.im/post/5c7a9e40e51d453f0a16c58d