search
HomeWeb Front-endFront-end Q&AWhat is the difference between es6 and commonjs

Difference: 1. CommonJS outputs a copy of the value, and ES6 outputs a reference to the value; 2. CommonJS is loaded at runtime, and ES6 is a compile-time output interface; 3. CommonJS require is loaded synchronously Modules, ES6's import is loaded asynchronously, and there is a resolution phase for independent module dependencies.

What is the difference between es6 and commonjs

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

What is the difference between es6 and commonjs

1. The CommonJS module outputs a copy of the value, while the ES6 module outputs a reference to the value

Let’s take a look at the usage of commonjs

1. First create a lib.js file

// lib.js
const counter = 3;
const incCounter = ()=>{
  counter++
}
module.exports = {
  counter,
  incCounter
}

2. Create a main.js again and import it using commonjs

// main.js
var lib = require('./lib');
console.log(lib)
console.log(lib.counter);  // 3
lib.incCounter();
console.log(lib.counter); // 3

After the lib.js module is loaded, its internal changes will not affect the output lib.counter. This is because mod.counter is a primitive type value and will be cached; let’s take a look at the usage of

esmodule

// lib.js
export let counter = 3;
export function incCounter () {
  counter++;
}
// main.js
import { counter, incCounter } from './util.mjs'
console.log(counter);  //3 
incCounter()
console.log(counter)  //4

ES6 module does not cache the running results, but dynamically Get the value from the loaded module locally, and the variable is always bound to the module in which it is located.

Supplement: Variables imported through esmodule cannot be reassigned or modified.

2. The CommonJS module is loaded at runtime, and the ES6 module is the output interface at compile time

// CommonJS模块
let { stat, exists, readFile } = require('fs');
 
// 等同于
let _fs = require('fs');
let stat = _fs.stat;
let exists = _fs.exists;
let readfile = _fs.readfile;

The essence of the above code is to load the fs module as a whole (that is, load all fs method), generate an object (_fs), and then read 3 methods from this object. This kind of loading is called "runtime loading", because this object can only be obtained at runtime, making it impossible to do "static optimization" at compile time. Therefore, commonjs is a method of loading modules only when it is run.

import { stat, exists, readFile } from 'fs';

The essence of the above code is to load 3 methods from the fs module, and other methods are not loaded. This kind of loading is called "compile-time loading" or static loading, that is, ES6 can complete module loading at compile time, which is more efficient than the loading method of CommonJS modules;

3. CommonJS module require () is a synchronous loading module. The import command of the ES6 module is asynchronous loading. There is an independent resolution phase of module dependencies.

Synchronous loading: The so-called synchronous loading means that the process of loading resources or modules will block subsequent Code execution;

Asynchronous loading: will not block the execution of subsequent code;

Let’s look at a case and create the following directory;

| -- a.js
| -- index.js
| -- c.js
// a.js
console.log('a.js文件的执行');
const importFun = () => {
  console.log(require('./c').c);
}
importFun()
module.exports = {
  importFun
}
// index.js
const A = require('./a');
console.log('index.js的执行');
// c.js
console.log('c.js的运行');
const c = 3
module.exports = {
  c
}

Execute the command node index. js

// a.js文件的执行
// c.js的运行
// 3
// index.js的执行

We will find that the content of require will block the execution of subsequent code. Because c.js is printed first, and then index.js is printed, so require() is loaded synchronously;

// a.js
console.log('a.js文件的执行');
export const importFun = () => {
  import('./c.js').then(({c})=>{
    console.log(c)
  })
}
importFun()
// index.js
import {importFun} from './a.js'
console.log('index.js的执行');
// c.js
console.log('c.js的运行');
export const c = 3
// 结果
// a.js文件的执行
// index.js的执行
// c.js的运行
// 3

It can be seen that import() loads resources asynchronously, because c .js is printed after index.js and will not block the execution of subsequent code;

Summary: The above are the differences between commonjs and esmodule

1: The CommonJS module outputs a copy of the value, and the ES6 module outputs a reference to the value.

2: The CommonJS module is loaded at runtime, and the ES6 module is a compile-time output interface.

3: The require() of the CommonJS module loads the module synchronously, and the import command of the ES6 module loads asynchronously, with an independent parsing phase of module dependencies

[Related recommendations: javascript video tutorialwebfrontend

The above is the detailed content of What is the difference between es6 and commonjs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is thedifference between class and id selector?What is thedifference between class and id selector?May 12, 2025 am 12:13 AM

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

CSS IDs vs Classes: The real differencesCSS IDs vs Classes: The real differencesMay 12, 2025 am 12:10 AM

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

CSS: What if I use just classes?CSS: What if I use just classes?May 12, 2025 am 12:09 AM

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and Class Selectors in CSS: A Beginner's GuideID and Class Selectors in CSS: A Beginner's GuideMay 12, 2025 am 12:06 AM

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.

Understanding the HTML5 Specification: Key Objectives and BenefitsUnderstanding the HTML5 Specification: Key Objectives and BenefitsMay 12, 2025 am 12:06 AM

Key goals and advantages of HTML5 include: 1) Enhanced web semantic structure, 2) Improved multimedia support, and 3) Promoting cross-platform compatibility. These goals lead to better accessibility, richer user experience and more efficient development processes.

Goals of HTML5: A Developer's Guide to the Future of the WebGoals of HTML5: A Developer's Guide to the Future of the WebMay 11, 2025 am 12:14 AM

The goal of HTML5 is to simplify the development process, improve user experience, and ensure the dynamic and accessible network. 1) Simplify the development of multimedia content by natively supporting audio and video elements; 2) Introduce semantic elements such as, etc. to improve content structure and SEO friendliness; 3) Enhance offline functions through application cache; 4) Use elements to improve page interactivity; 5) Optimize mobile compatibility and support responsive design; 6) Improve form functions and simplify verification process; 7) Provide performance optimization tools such as async and defer attributes.

HTML5: Transforming the Web with New Features and CapabilitiesHTML5: Transforming the Web with New Features and CapabilitiesMay 11, 2025 am 12:12 AM

HTML5transformswebdevelopmentbyintroducingsemanticelements,multimediacapabilities,powerfulAPIs,andperformanceoptimizationtools.1)Semanticelementslike,,,andenhanceSEOandaccessibility.2)Multimediaelementsandallowdirectembeddingwithoutplugins,improvingu

ID vs. Class in CSS: A Comprehensive ComparisonID vs. Class in CSS: A Comprehensive ComparisonMay 11, 2025 am 12:12 AM

TherealdifferencebetweenusinganIDversusaclassinCSSisthatIDsareuniqueandhavehigherspecificity,whileclassesarereusableandbetterforstylingmultipleelements.UseIDsforJavaScripthooksoruniqueelements,anduseclassesforstylingpurposes,especiallywhenapplyingsty

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools