Modular solution: CommonJs & ESModule

CommonJs (cjs)

  • cjs is Node's modular specification, using require& exportsfor 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 requiredata
require(`./${
      
      a}`);

For a detailed introduction, see: CommonJs



ESModule (esm)

  • esm is a modular specification of ES6, using import& exportfor 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 importarrays
// 报错
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

  1. 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

  2. cjs is loaded at runtime , and esm is loaded at compile
    time ∴ The import statement of esm importwill be automatically promoted

  3. cjs is dynamic loading, esm is static loading
    ∴ esm cannot import data through variables

Guess you like

Origin blog.csdn.net/Superman_H/article/details/126911615