commonJS and ESM

CommonJS

 1. Community Standards

 2. The function implements the require() function

 3. node environment

 4. Dynamic dependencies (dependencies need to be determined after the code runs)

 5. Dynamic dependencies are executed synchronously

 ESM

 1. Official Standards

 2. Implemented using the new syntax

 3. All environments support

 4. Both static and dynamic dependencies are supported (static dependencies: dependencies must be determined before the code runs; dynamic dependencies: routes are used for lazy loading)

 5. Dynamic dependencies are asynchronous

 6. Symbol binding

 What is the difference between CommonJS and ES modules?

CMJ is a community standard, ESM is an official standard

CMJ is modularization using API (functions), ESM is modularization using new syntax

CMJ is only supported in the node environment, and ESM is supported in various environments

CMJ is a dynamic dependency, executed synchronously. ESM supports both dynamic and static, and dynamic dependencies are executed asynchronously.

ESM has symbol binding when imported, CMJ is just ordinary function call and assignment

What is the difference between export and export default?

export is a common export, also known as a named export. As the name suggests, the data it exports must be named, such as variable definitions and function definitions. In the exported module object, the name is the attribute name of the module object. There can be multiple named exports in a module

export default is the default export, and the name in the module object is fixed as default, so there is no need to name it, and an expression or literal is usually exported. There can be only one default export in a module.

Example questions about symbol binding

// module counter
var count = 1;
export {count}
export function increase(){
  count++;
}

// module main
import { count, increase } from './counter';
import * as counter from './counter';
const { count: c } = counter;
increase();
console.log(count); // 2 
console.log(counter.count); //2
console.log(c); //1  因为c不是符号绑定,是一个全新的空间,所以值不会改变

Guess you like

Origin blog.csdn.net/m0_54581080/article/details/126262449