JavaScript – CommonJS
前言
既然写了 JavaScript – ES Module, 也就顺便些 CommonJS 呗, 建议先看 ES Module 那篇.
参考
Youtube – Require vs Import Javascript
Youtube – Node and Express.js Fundamentals - Common.js Modules
Export 语法
逐个 export
// my-module.js exports.myVar = "myVar"; exports.myFunction = () => {}; console.log(this.myVar); // 如果当前要用到 myVar, 可以使用 this, this 指向当前 module
这个写法不是很好看...
批量 export
const myVar = "myVar"; const myFunction = () => {}; module.exports = { myVar, myFunction, };
export default
// my-module.js const myVar = "myVar"; module.exports = myVar;
但它不能像 ES Module 那样又 export default 又 export 其它的哦.
别名 alias
module.exports = {
yourVar: myVar,
myFunction,
};
它就是个对象 key 而已.
Import 语法
// my-module.js const myVar = "myVar"; function myFunction() {} module.exports = { myVar, myFunction, }; // main.js const { myVar, myFunction } = require("./my-module.js"); myFunction(); console.log(myVar);
别名 alias
const { yourVar: myVar, myFunction } = require("./my-module.js");
用解构对象就可以了.
与 ES Module 不同之处
CommonJS 只用于 Node.js.
CommonJS 是 runtime 的, ES Module 是 compile time 的
- 比如说, import 会置顶, 那么就会先被执行, 而 require 不会, 它会等到 runtime 运行到那一行它才去加载执行.
require 可以写在 if, function 里面, 类似 ES Module 的 dynamic import()
export 的值是 cache 来的, 它不会同步 (ES Module 会)
require 的 variable 可以修改, ES Module 则是 read-only.
还有许多的不同啦, 总之它们不兼容. 所有的兼容方案, 都是做出了一些严格要求的才能实现的. 比如不允许 if 里面有 require 等等.