当前位置:网站首页>ES6 modularization +commonjs
ES6 modularization +commonjs
2022-07-26 04:36:00 【See morning mist without Chang'an】
ES6 Modular Introduction
stay ES6 Before the birth of modular specification ,JavaScript The community has tried to propose AMD、CMD、CommonJS Isomodular specification .
however , These modular standards proposed by the community , There are certain differences and limitations , It's not a common modular standard for browsers and servers . for example :
- AMD and CMD For browser side JavaScript modularization
- CommonJS For server side JavaScript modularization
therefore ,2015 year ES6 Officially defined JavaScript Modular standards .
ES6 Modular specification is a general modular development specification for browser and server . Its appearance greatly reduces the modular learning cost of front-end developers , Developers don't have to learn any more AMD、CMD or CommonJS Isomodular specification .
ES6 It is defined in the modular specification :
- Every js File is a separate module
- Import other module members to use import keyword
- Shared module members use export keyword
ES6 Module Will automatically adopt strict mode , This is in ES5 There is an option . Previously, we could choose whether to add ”use strict” To control the strict mode , stay ES6 Module It doesn't matter whether there is ”use strict”, Will adopt strict mode .
stay NodeJS Use in ES6 modularization
node.js Only supported by default in CommonJS Modular specification , If you want to use ES6 modularization , The following two-step configuration is required :
- Make sure that... Is installed v14.15.1 Or later node.js
- stay package.json Add... To the root node of "type":"module" node .


ES6 Modular export basic syntax
ES6 The modularization of mainly includes the following 3 Usage :
- The default is derived And The default import
- Export... On demand And Import on demand
- Import directly and execute The code in the module
1) Default export and default import
The default is derived
let n1 = 10;
let n2 = 20;
function show(){
}
export default{
n1,
show
}
Be careful : In each module , The default is derived export default Only one use is allowed , Otherwise, an error will be reported .
The default import
import m1 from './01_ The default is derived .js'
console.log(m1)

The default import time is Receiving name You can do whatever you want , As long as it is a legal member name .
perform

2) On demand export and on demand import
Export... On demand
export let s1 = 'aaa'
export let s2 = 'ccc'
export function say() {
}
Import on demand
import {
s1, s2, say } from './03. Export... On demand .js'
console.log(s1)
console.log(s2)
console.log(say)
- Can be used in each module many times Export... On demand
- Member names imported on demand It has to be with Name of the on-demand Export bring into correspondence with
- On demand import , have access to as keyword Rename
- On demand import can be used with default import
On demand import is used with default import

3) Directly import and execute the code in the module
If you just want to execute the code in a module , You don't need to get members shared outside the module , here , You can import and execute module code directly .

CommonJS
CommonJS By JavaScript Community in 2009 The inclusion module proposed in 、 file 、IO、 A range of standards including the console . stay Node.js In the implementation of CommonJS Part of the standard , And made some adjustments on its basis . What we say CommonJS Module and Node.js The implementation in is not exactly the same , Now generally speaking CommonJS It's actually Node.js Version in , Not its original definition .
CommonJS It was originally designed for the server , Until there is Browsefify—— One runs on Node.js Module packaging tool in the environment , It can be CommonJS The module is packaged as a single file that the browser can run . This means that the client code can also follow CommonJS Standards to prepare .
Node.js Followed CommonJS Modular specification ,CommonJS It specifies the characteristics of modules and how they depend on each other .
CommonJS Regulations :
- Inside each module ,module Variable represents the current module
- module Variable is an object , its exports attribute ( namely module.exports) It's an external interface .
- Load a module , In fact, the module is loaded module.exports attribute .require() Method for loading modules .
Node Module in
Node.js Module in , Depending on the source , Divided into 3 Categories: , Namely :
- Built-in module ( The built-in module is made up of Node.js Official , for example fs、path、http etc. )
- Custom module ( Each user created .js file , Are custom modules )
- Third-party module ( Modules developed by third parties , You need to download it before using it )
Use require Load module
stay CommonJS Use in require Do module import , Use require() Method , You can load built-in modules 、 User defined module 、 Use third-party modules .
Be careful : Use require() Method to load the module , Will execute the code in the loaded module . Use require(), It can be omitted .js suffix .
When we require There are two situations when using a module :
- require This is the first time that the module is loaded . And then it will First execute the module , And then export the content .
- require Has been loaded . At this time, the code of the module will not be executed again , It directly exports the results obtained after the last execution .
The module will have a module Object is used to store its information , This object has an attribute loaded Used to record whether the module has been loaded . Its default value is false, When the module is loaded and executed for the first time, it will be set to true, Later, when loading again, it was found that module.loaded by true, The module code will not be executed again .


Module scope
Variables defined in the custom module 、 Method and other members , Can only be accessed within the current module , Access restrictions at this module access level , It's called module scope .
About module object
Every .js Each custom module has a module object , It stores information related to the current module .
module.exports object
In the custom module , have access to module.exports object , Share the members in the module , For external use .
For the outside world require() Method to import a custom module , What you get is module.exports The object that is pointed to .
Use module.exports Share members out

Be careful : Use require() Method when importing a module , The result of the import , Always use module.exports The object pointed to shall prevail .

exports object
because module.exports It's more complicated to write , To simplify the code for sharing members out ,Node Provides exports object . By default ,exports and module.exports Point to the same object . The final shared result , Or to module.exports The object pointed to shall prevail .

In the use of exports Pay attention to , Don't give it directly to exports assignment , Otherwise, it will fail . If exports Points to a new object ,module.exports But it's still the original empty object .
Be careful : The export statement does not represent the end of the module , stay module.exports or exports The following code will still execute as usual .
exports and module.exports The use of mistakes

边栏推荐
- Face database collection summary
- Analyzing the curriculum design evaluation system of steam Education
- Phaser (I): platform jumping collection game
- Offline installation of idea plug-in (continuous update)
- 二、国际知名项目-HelloWorld
- What if win11 cannot wake up from sleep? Solution of win11 unable to wake up during sleep
- 软考回顾及计划
- 【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(八)
- Recursive implementation of exponential enumeration
- UE4 two ways to obtain player control
猜你喜欢

Codeforces Round #807 (Div. 2)

Build a maker Education Laboratory for teenagers

Array sort 1

Yapi installation

Phaser(一):平台跳跃收集游戏

ES6模块化+CommonJS

Getting started with mongodb Basics

UE4 two ways to obtain player control

Use Baidu PaddlePaddle easydl to complete garbage classification

TIA botu WinCC Pro controls the display and hiding of layers through scripts
随机推荐
7、 Restful
2022 Henan Mengxin League game (3): Henan University a - corn cannon
Solve the error string value: '\xf0\x9f\x98\xad',... 'for column' commentcontent 'at row 1
Array sort 1
Sangi diagram of machine learning (for user behavior analysis)
Function knowledge points
1、 Basic introduction
使用百度飞桨EasyDL完成垃圾分类
Analyzing the curriculum design evaluation system of steam Education
建设面向青少年的创客教育实验室
Swiftui one day crash
[uoj 429] runs (inclusive) + a little record about Lyndon tree and its application
2022 Henan Mengxin League game (3): Henan University J - magic number
七、RESTful
Js手写函数之节流防抖函数
How does win11 change the power mode? Win11 method of changing power mode
十一、异常处理器
AWS Support Plan
Rotate array minimum number
An SQL server queries the latest records as of a certain date