当前位置:网站首页>JS modularization
JS modularization
2022-06-26 07:13:00 【_ Language and ink】
js modularization
One 、 background
JS Simple page design : Page animation + Form submission
No modularity or The concept of namespace
JS The demand for modularity is growing
Two 、 The development of modularization
1. childhood : No modularity
1. You need to add some different js: Animation 、 Forms 、 Format, etc
2. Varied js The files are divided into different files
3. Different files are referenced by the same template
<script src="jquery.js"></script>
<script src="main.js"></script>
<script src="dep1.js"></script>
//……
recognition :
File separation is the first step of the most basic modularization
shortcoming :
Pollution global scope , It is not conducive to the development of large-scale projects and the co construction of multi person teams
2. Growing period : IIFE( Optimization of grammar side )
IIFE: Immediately Invoked Function Expression, The function expression that is called immediately . That is to say Call the function immediately after it is declared .
Using the block level scope of a function , Define a function , Execute now , A simple module has been implemented .
Try to define the simplest module :
const iifeModule = (() => {
let count = 0;
return {
increase: () => ++count;
reset: () => {
count = 0;
}
}
})();
iifeModule.increase();
iifeModule.reset();
Questioning 1: When there are additional dependencies , How to optimize IIFE Related codes
answer : Pass parameters in the form of parameters
Optimize 1: Relying on other modules IIFE
const iifeModule = ((dependencyModule1, dependencyModule2) => {
let count = 0;
return {
increase: () => ++count;
reset: () => {
count = 0;
}
}
})(dependencyModule1, dependencyModule2);
iifeModule.increase();
iifeModule.reset();
Questioning 2: Understanding early jquery Dependency handling and module loading scheme ?/ Understand tradition IIFE How to solve the problem of multi dependency
answer :IIFE Add transmission parameters for deployment
actually ,jQuery And so on revealing Writing .
const iifeModule = ((dependencyModule1, dependencyModule2) => {
let count = 0;
const increase = () => ++count;
const reset = () => {
count = 0;
}
// Only return methods , There is no need to care about how it is implemented
return {
increase, reset
}
})(dependencyModule1, dependencyModule2);
iifeModule.increase();
iifeModule.reset();
3. mature period
CJS-Commonjs
node.js To develop
features :
- adopt module+exports Area external exposure interface
- adopt require To call other modules
Module organization :
main.js file
// Introduction part
const dependencyModule1 = require(./dependencyModule1);
const dependencyModule2 = require(./dependencyModule2);
// processing section
let count = 0;
const increase = () => ++count;
const reset = () => {
count = 0;
}
// Do something related to introducing dependencies ……
// Expose the interface part
exports.increase = increase;
exports.reset = reset;
module.exports = {
increase, reset
}
Module usage :
const {
increase, reset } = require('./main.js');
increase();
reset();
Questioning 1: Actually execute the processing
(function (thisValue, exports, require, module) {
const dependencyModule1 = require(./dependencyModule1);
const dependencyModule2 = require(./dependencyModule2);
// Business logic ……
}).call(thisValue, exports, require, module);
advantage :
CommonJs Take the lead in realizing , Resolve dependencies at the framework level , The problem of global variable pollution
shortcoming :
It mainly aims at the solution of the server . It is not so friendly to the processing and integration of Ibrahimovic .
The new problem : Asynchronous rely on
AMD standard
Through asynchronous loading + Allows you to specify callback functions
The classic implementation framework is :require.js
New definition method :
// adopt define To define a module , then require Loading
/* define params: Module name , Rely on the module , Factory method */
define(id, [depends], callback);
require([module], callback);
Module definition method
define('amdModule', ['dependencyModule1', 'dependencyModule2'], (dependencyModule1, dependencyModule2) => {
// Business logic
// processing section
let count = 0;
const increase = () => ++count;
const reset = () => {
count = 0;
}
return {
increase, reset
}
})
Introduce modules :
require(['amdModule'], amdModule => {
amdModule.increase();
})
Questioning 2: If in AMDmodule Want to be compatible with existing code , What do I do
define('amdModule', [], require => {
// Introduction part
const dependencyModule1 = require(./dependencyModule1);
const dependencyModule2 = require(./dependencyModule2);
// processing section
let count = 0;
const increase = () => ++count;
const reset = () => {
count = 0;
}
// Do something related to introducing dependencies ……
return {
increase, reset
}
})
Questioning 3:AMD Use in revealing
define('amdModule', [], (require, export, module) => {
// Introduction part
const dependencyModule1 = require(./dependencyModule1);
const dependencyModule2 = require(./dependencyModule2);
// processing section
let count = 0;
const increase = () => ++count;
const reset = () => {
count = 0;
}
// Do something related to introducing dependencies ……
export.increase = increase();
export.reset = reset();
})
define('amdModule', [], require => {
const otherModule = require('amdModule');
otherModule.increase();
otherModule.reset();
})
Questioning 4: compatible AMD&CJS/ How to determine CJS and AMD
UMD Appearance
(define('amdModule', [], (require, export, module) => {
// Introduction part
const dependencyModule1 = require(./dependencyModule1);
const dependencyModule2 = require(./dependencyModule2);
// processing section
let count = 0;
const increase = () => ++count;
const reset = () => {
count = 0;
}
// Do something related to introducing dependencies ……
export.increase = increase();
export.reset = reset();
}))(
// The goal is to differentiate at one time CommonJSorAMD
typeof module === "object"
&& module.exports
&& typeof define !== "function"
? // yes CJS
factory => module.exports = factory(require, exports, module)
: // yes AMD
define
)
advantage :
Suitable for loading asynchronous modules in the browser , Multiple modules can be loaded in parallel
shortcoming :
There will be introduction costs , Can't load on demand
CMD standard
Load on demand
The main application framework sea.js
define('module', (require, exports, module) => {
let $ = require('jquery');
// jquery Related logic
let dependencyModule1 = require('./dependecyModule1');
// dependencyModule1 Related logic
})
advantage :
Load on demand , Rely on proximity
Rely on packaging , The loading logic exists in each module , Expand the module volume
Questioning 5:AMD&CMD difference
Rely on proximity , Load on demand .
AMD Respect dependence before 、 Advance execution ,CMD Advocate dependence on proximity 、 Delay the
ES6 modularization : To a new era
New definition :
Introduce keywords — import
Export keywords — export
Module introduction 、 Where to export and define
// Introduction area
import dependencyModule1 from './dependencyModule1.js';
import dependencyModule2 from './dependencyModule2.js';
// Implement code logic
let count = 0;
export const increase = () => ++count;
export const reset = () => {
count = 0;
}
// Export area
export default {
increase, reset
}
Where the template is introduced
<script type="module" src="esModule.js"></script>
node in :
import {
increase, reset } from './esModule.mjs';
increase();
reset();
import esModule from './esModule.mjs';
esModule.increase();
esModule.reset();
Questioning 6: Dynamic modules
Investigate export promise
ES11 Native solutions :
import('./esModule.js').then(dynamicEsModule => {
dynamicEsModule.increase();
})
advantage ( Importance ): Through a most unified form of integration js The modular
shortcoming ( limitations ): In essence Run dependency analysis
New ideas to solve modularization : Front-end engineering
Full body :
webpack As the core of engineering + mvvm Frame componentization + Design patterns
边栏推荐
- Calculate division in Oracle - solve the error report when the divisor is zero
- Young man, do you know the original appearance of kotlin association process?
- Crosslinked metalloporphyrin based polyimide ppbpi-h) PPBP Mn; PBP-Fe; PPBPI-Fe-CR; Ppbpi Mn CR product - supplied by Qiyue
- Cache usage
- 一文搞懂Glide,不懂来打我
- 执行npm install -g serve时报错权限权限问题解决方案
- Market survey of China's coal to liquid industry and analysis report on investment competitiveness during the "14th five year plan" 2022-2027
- MXNet对NIN网络中的网络的实现
- SQL
- Liujinhai, chief architect of zhongang Mining: according to the analysis of fluorite supply and demand, it is estimated that the fluorine coating market has great potential
猜你喜欢
Crosslinked porphyrin based polyimide ppbpi-2, ppbpi-1-cr and ppbpi-2-cr; Porous porphyrin based hyperbranched polyimide (ppbpi-1, ppbpi-2) supplied by Qiyue
Invalid problem of self defined map used by Gaode map
【推荐10个 让你轻松的 IDEA 插件,少些繁琐又重复的代码】
One chip realizes functions such as spray 𞓜 ws2812 drive | key touch | LED display | voice broadcast chip and simplifies the design of humidifier products
MySQL
NumPy学习挑战第四关-NumPy数组属性
Shengshi Haotong enterprise wechat sector creates a digital ecological community
[feature extraction] feature selection of target recognition information based on sparse PCA with Matlab source code
大厂面试TCP协议经典十五连问!22张图让你彻底弄明白
【图像增强】基于人工多重曝光融合AMEF实现图像去雾附matlab代码
随机推荐
Global and Chinese silicon carbide monocrystal furnace market survey and future production and marketing demand analysis report 2022-2027
Promise API for getting started with the web
[feature extraction] feature selection of target recognition information based on sparse PCA with Matlab source code
NumPy学习挑战第四关-NumPy数组属性
QPS
Numpy learning challenge level 5 - create array
同花顺究竟如何开户,网上开户是否安全么?
One chip realizes functions such as spray 𞓜 ws2812 drive | key touch | LED display | voice broadcast chip and simplifies the design of humidifier products
Sanic based services use celery to complete dynamic modification timing tasks
When asked during the interview, can redis master-slave copy not answer? These 13 pictures let you understand thoroughly
少年,你可知 Kotlin 协程最初的样子?
C#实现给DevExpress中GridView表格指定列添加进度条显示效果——代码实现方式
Redis series - five common data types day1-3
13. Mismatch simulation of power synthesis for ads usage recording
[image fusion] MRI-CT image fusion based on gradient energy, local energy and PCA fusion rules with matlab code
5,10,15,20-tetra (4-bromophenyl) porphyrin (h2tppbr4) /5.2.15,10,15,20-tetra [4-[(3-aminophenyl) ethynyl] phenyl] porphyrin (tapepp) Qiyue porphyrin reagent
How to convert Unicode into Chinese characters in Excel
China's audio industry competition trend outlook and future development trend forecast report 2022 Edition
一文深入底层分析Redis对象结构
QPS