当前位置:网站首页>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=ageb.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 nameb.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>边栏推荐
- What about the pointer in neural network C language
- 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
- 喜讯!科蓝SUNDB数据库与鸿数科技隐私数据保护管理软件完成兼容性适配
- You Yuxi, coming!
- ThinkPHP URL 路由简介
- three.js打造酷炫下雪效果
- Is it reliable to open an account on Tongda letter with your mobile phone? Is there any potential safety hazard in such stock speculation
- Laravel 服务提供者实例教程 —— 创建 Service Provider 测试实例
- 统计学习方法——感知机
- TiDB For PostgreSQL和YugabyteDB在Sysbench上的性能对比
猜你喜欢

无线传感器网络--ZigBee和6LoWPAN

强化实时数据管理,英方软件助力医保平台安全建设

航運船公司人工智能AI產品成熟化標准化規模應用,全球港航人工智能/集裝箱人工智能領軍者CIMC中集飛瞳,打造國際航運智能化標杆

尤雨溪,来了!

模仿企业微信会议室选择

Sysom case analysis: where is the missing memory| Dragon lizard Technology

Three. JS introductory learning notes 10:three JS grid
![Unity drawing plug-in = = [support the update of the original atlas]](/img/b0/92114ffb1f168a1f27125db46c6797.jpg)
Unity drawing plug-in = = [support the update of the original atlas]

Lecturer solicitation order | Apache seatunnel (cultivating) meetup sharing guests are in hot Recruitment!

Eye of depth (VII) -- Elementary Transformation of matrix (attachment: explanation of some mathematical models)
随机推荐
深度之眼(七)——矩阵的初等变换(附:数模一些模型的解释)
Power of leetcode-231-2
hellogolang
Eye of depth (VII) -- Elementary Transformation of matrix (attachment: explanation of some mathematical models)
Strengthen real-time data management, and the British software helps the security construction of the medical insurance platform
torch.numel作用
通知Notification使用全解析
10 schemes to ensure interface data security
一个普通人除了去工厂上班赚钱,还能干什么工作?
What are compiled languages and interpreted languages?
Excessive dependence on subsidies, difficult collection of key customers, and how strong is the potential to reach the dream of "the first share of domestic databases"?
目标跟踪常见训练数据集格式
Description of vs common shortcut keys
Good news! Kelan sundb database and Hongshu technology privacy data protection management software complete compatibility adaptation
Statistical learning method -- perceptron
修改配置文件后tidb无法启动
Shader basic UV operations, translation, rotation, scaling
Laravel 中config的用法
Bidding announcement: 2022 Yunnan Unicom gbase database maintenance public comparison and selection project (second) comparison and selection announcement
Iptables only allows the specified IP address to access the specified port