commonJS模块化规范简单使用和了解
导出方式
- 导出多个成员
exports.a = 12;exports.b = 'hello';exports.c = function () {};
- 导出单个成员
module.exports = 'hello';
以下情况会覆盖:
module.exports = 'hello';module.exports = function () {};// 这样只导出了function方法
可以这样导出多个对象:
module.exports = { a: 123, b: function () {}}
加载模块
var 自定义变量名称 = require('模块');
原理解析
可以这样认为:
基于commonJS,每个模块内部有一个自己的module
在module中有一个exports的成员对象
模块默认最后return 出 自己的module.exports对象,供其他模块使用
可以通过这段代码理解模块
var module = { exports: { // 导出的各种属性,成员 }}var exports = module.exports;// 把module.exports赋值给exports,可以使用exports导出内容//但是不能这样使用(单个导出)// exports = "dadad"// exports = {}return module.exports;
- 基于原理的一些规则总结