当前位置:网站首页>JS modularization
JS modularization
2022-07-07 16:20:00 【Bashan queer dialect】
Catalog
1. The history of modularity
Back end languages have long been modular , Such as python etc. , but JS Not for a long time .
The result is js Can't save a large file , Split into multiple small files , Then splice it together , This is developing large-scale 、 Complex projects are very difficult .
But though JS The official does not give modularity , But the developer community has given birth to several modular ideas , Or specification , Such as AMD、CMD、CommonJS etc. .
In these specifications ,AMD and CMD Modularization can be realized on the browser side ,CommonJS More suitable for Node End , Because it cannot solve the asynchronous loading problem on the browser side by default , Therefore, it is not suitable for browser side .
2015 year , stay ES6 At the time of release ,JS The government finally gave its own Modular Scheme ES6 Module(ESM), This modular scheme can replace 、AMD、CMD and CommonJS, Support at the same time Modularization of browser and server , Finally achieve a unified modular scheme .
No matter what kind of modular solution , All support some basic concepts
- One js File is a module
- The data in the module is independent , Other modules cannot be accessed by default
Let's focus on CommonJS and ESM
2. CommonJS
This modular specification is similar to node.js Accompany each other , For a long time ,Node Only this modular scheme is supported .
Use exports perhaps module.exports Burst data , Use require Load module
a.js export
let name='yhb'
module.exports.name=name
let age=20
module.exports.age=age
b.js Import
const a_modue=require('./a')
console.log(a_modue)
a_module It's an object
{ name: 'yhb', age: 20 }
a.js You can also export data in the following way
let name = 'yhb'
let age = 20
module.exports = {
name,
age
}
Above is CommonJS The most basic content of modularity
3. ES6 modularization
ES6 Modular abbreviation ESM
ESM Burst data usage export perhaps export default, Load data using import
It also supports both server and browser
3.1 node Use in ESM
node If you want to change to use ESM, Need to be in package.json Add type attribute , And set the value to module(type The default value of the property is commonjs)
type":"module"
a.js
export let name = 'yhb'
export function f1() {
console.log('f1')
}
b.js
import {name,f1} from './a.js'
f1()
a.js You can also export to the following
let name='yhb'
let age=20
function sayHello(){
console.log('hello')
}
export {name,age,sayHello}
b.js
import {name,age,sayHello} from './a.js'
console.log(name)
console.log(age)
sayHello()
b.js When loading modules in , Except like above , Specify the data in the module to be loaded separately , The whole module can also be loaded
import * as a_module from './a.js'
console.log(a_module.name)
console.log(a_module.age)
a_module.sayHello()
In the code above , Developers need to know a.js The name of the variable or function in the module , When loading or using , The name cannot be misspelled ,
Like the following code , because a.js There is no aaa Variable , Therefore, the following introduction will report an error
import {name,aaa} from './a.js'
Is it possible to , Developers do not need to know the names of variables or functions in the module , It can also be used ?
Use... In the module export default Grammar can solve this problem well
a.js
let name='yhb'
export default name
b.js
import sss from './a.js'
console.log(sss)
export default It is equivalent to deriving a called default The variable of (default Variables and name The values of the variables are the same ),b.js You can give it a name at will
export default The exported can also be a function , Because the function can be named outside the module at will , So here we use anonymous functions , The function name has no meaning here
export default function (){
console.log('sayHello')
}
b.js
import f1 from './a.js'
f1()
because expor default Is the default output , So there can only be one in each module export default sentence
export default Except like above , Export a variable or function , You can also export an object
let name = 'yhb'
let age = 20
export default {
name,
age
}
When other modules are loaded , Not like not using default The way of writing time
import {name,age} from './a.js'
But it must be written like this
import a_module from './a.js'
console.log(a_module.name)
console.log(a_module.age)
3.2 The browser uses ESM
a.js
let name = 'yhb'
let age = 20
export {
name,
age
}
b.js
import {name,age} from './a.js'
function printInfo(){
console.log(`${name} This year, ${age} Year old `)
}
printInfo()
index.html
<script type="module" src="./b.js"></script>
If b.js No call in printInfo, But export
import {name,age} from './a.js'
function printInfo(){
console.log(`${name} This year, ${age} Year old `)
}
export {printInfo}
index.html If you want to call printInfo Words , It needs to be written like this
<script type="module">
import {printInfo} from './b.js'
printInfo()
</script>
边栏推荐
- 安科瑞电网智能化发展的必然趋势电力系统采用微机保护装置是
- 95.(cesium篇)cesium动态单体化-3D建筑物(楼栋)
- 如何在shell中实现 backspace
- php 自带过滤和转义函数
- You Yuxi, coming!
- Numpy --- basic learning notes
- C4D learning notes 1- animation - animation key frames
- Unity3D_ Class fishing project, bullet rebound effect is achieved
- Laravel 中config的用法
- A link opens the applet code. After compilation, it is easy to understand
猜你喜欢
讲师征集令 | Apache SeaTunnel(Incubating) Meetup 分享嘉宾火热招募中!
Numpy -- data cleaning
AE learning 01: AE complete project summary
torch. Numel action
SPI master RX time out interrupt
Eye of depth (VI) -- inverse of matrix (attachment: some ideas of logistic model)
C4D learning notes 2- animation - timeline and time function
Plate - forme de surveillance par étapes zabbix
Description of vs common shortcut keys
Shipping companies' AI products are mature, standardized and applied on a large scale. CIMC, the global leader in port and shipping AI / container AI, has built a benchmark for international shipping
随机推荐
How to determine whether the checkbox in JS is selected
PHP中exit,exit(0),exit(1),exit(‘0’),exit(‘1’),die,return的区别
Good news! Kelan sundb database and Hongshu technology privacy data protection management software complete compatibility adaptation
Three. JS introductory learning notes 05: external model import -c4d into JSON file for web pages
保证接口数据安全的10种方案
47_ Contour lookup in opencv cv:: findcontours()
Shandong old age Expo, 2022 China smart elderly care exhibition, smart elderly care and aging technology exhibition
Three. JS introductory learning notes 08:orbitcontrols JS plug-in - mouse control model rotation, zoom in, zoom out, translation, etc
Asyncio concept and usage
Apache Doris刚“毕业”:为什么应关注这种SQL数据仓库?
C4D learning notes 2- animation - timeline and time function
Notification uses full resolution
Three. JS introductory learning notes 15: threejs frame animation module
Iptables only allows the specified IP address to access the specified port
持续创作,还得靠它!
The inevitable trend of the intelligent development of ankerui power grid is that microcomputer protection devices are used in power systems
Xcode Revoke certificate
2022第四届中国(济南)国际智慧养老产业展览会,山东老博会
L'application à l'échelle de la normalisation mature des produits ai des compagnies maritimes, cimc, leader mondial de l'intelligence artificielle portuaire et maritime / intelligence artificielle des
Eye of depth (VI) -- inverse of matrix (attachment: some ideas of logistic model)