CommonJS
CommonJS是一种被广泛使用的js模块化规范,核心思想是通过require方法来同步加载依赖的其他模块,通过module.exports导出需要暴露的接口。
采用 CommonJS 导入及导出的代码如下:
//导入
const moduleA = require ( ’. / moduleA’);
//导出
module .exports = moduleA.someFunc;
CommonJS 的优点在于:
- 代码可复用于 Node.js 环境下井运行,例如做同构应用:
通过 Npm 发布的很多第三方模块都采用了 CommonJS 规范。
CommonJS 的缺点在于:
- 这样的代码无法直接运行在浏览器环境下,必须通过工具转换 成标准的 ES5。
CommonJS 还可以细分为 CommonJSl 和 CommonJS2,区别在于 CommonJSl 只能通过 exports . XX = XX 的方式导出,而 CommonJS2 在 CommonJSl 的基础上加入了 module.exports = XX 的导出方式。 CommonJS 通常指 CommonJS2。