跳至主要內容

模块化

望间代码Node.js小于 1 分钟

模块化

将一个大文件拆分成多个独立并且互相依赖的模块

加载模块

require("module");

加载模块时,会立即执行模块中的代码

module 对象

存储了当前模块的相关信息

每个 js 自定义模块都有一个 module 对象

module.exports 对象

将模块内的成员共享出去

module.exports.属性/方法名 = 功能;

使用 require 方法导入自定义模块时,得到的就是 module.exports指向的对象

module.exports默认是一个空对象

exports 对象

module.exports === exports

exports.属性/方法名 = 功能;

exportsmodule.exports 最好不要同时使用,容易搞混

规范

CommonJS 规范

  1. 每个模块内部,module 代表当前模块
  2. module 是一个对象,它的 exports 属性是对外接口
  3. require 方法用来加载模块,加载的就是module.exports对象
上次编辑于:
贡献者: ViewRoom