CommonJs (cjs)
-
cjs is Node's modular specification, using
require
&exports
for import and export -
cjs can be used in node environment & webpack environment, but not in browser
-
If the front-end project is in webpack, it can also be understood that both browser and Node support
Some modules only support cjs, such as ms, but it does not affect its use in front-end projects (through webpack).
However, if it is directly introduced in the browser through cdn, there will be problems
/* cjs1.js */
module.exports = 10; // 导出一个数值
console.log("cjs1.js");
/* cjs2.js */
const num = require("./cjs1"); // 导入数据
console.log("cjs1", num); // cjs1 10
- cjs is dynamically loaded, and can pass variable
require
data
require(`./${
a}`);
For a detailed introduction, see: CommonJs
ESModule (esm)
- esm is a modular specification of ES6, using
import
&export
for import and export - Both Node and browser support esm
/* esm1.js */
export let age = 18;
console.log("esm1.js");
/* esm2.js */
import {
age } from "./esm1.js";
console.log(age); // 18
- esm is statically imported, and Tree Shaking can be performed during compilation to reduce js volume
- Because esm is a static import, it cannot pass variable
import
arrays
// 报错
import {
'f' + 'oo' } from 'my_module'; // 不能使用 [表达式] 接收导入数据
// 报错
let module = 'my_module';
import {
foo } from module; // 不能使用 [变量] 作为被导入文件的路径
// 报错:不能在语句内进行导入
if (true)
import {
foo } from 'module1';
- If dynamic import is required, esm can also use
import("./module.js")
to import
For details, see: ESModule
cjs & esm
-
cjs outputs a copy of the value , and esm outputs a reference
to the value ∴ After the data source is updated, the data exported by esm will also be updated -
cjs is loaded at runtime , and esm is loaded at compile
time ∴ The import statement of esmimport
will be automatically promoted -
cjs is dynamic loading, esm is static loading
∴ esm cannot import data through variables