CommonJS
是 Node
应用的模块化规范。
它原先的名字是 ServerJS
,顾名思义,指的是服务端的模块化规范。
后来社区为了兼容浏览器端,更名为 CommonJS
,意图一统前后端。
不幸的是,社区在指定浏览器的模块化标准上有了分歧,进而衍生了 AMD
、CMD
等等。
更多细节可参考玉伯的前端模块化开发那点历史
1.基本用法
Node
中的模块化用起来非常简单。
导入模块:
js
// Node的内置模块
var path = require('path')
// node_modules中的第三方模块
var vue = require('vue')
// 自定义模块
var { getName } = require('./utils')
导出模块:
js
// 利用module.exports
module.exports = {
msg: 'Hello world'
}
也可以使用 exports
:
js
// 利用exports
exports.time = new Date()
2.module.exports与exports
exports
默认指向module.exports
,相当于文件头部有一条语句var exports = module.exports
。exports
不能重新赋值,会导致指向更改。同一文件中,
module.exports
与exports
不能同时使用。同时使用的话,只有module.exports
会起作用。如果对这两个方式纠结,那么建议统一使用
module.exports
。
3.require
require
导入的是初始化拷贝,后续在模块里的更改,并不会影响到值。require
同一模块时,模块只会加载一次。后续调用,会从缓存中读取。require
是动态读取,即可以在使用的任何地方调用。而EsModule
只能写在文件头部。