June learning Record
preface
In June, WHEN I needed to package a project, I had no clue at all. I didn’t know about it before, but I knew webpack and other tools were used to package a project, but I didn’t know the format and principle of the package (I may have seen it, but I just forgot). Therefore, I reflected on myself, when expanding knowledge, we must understand its history and principle, do not think that it will remember a few API, as long as we know the principle, based on the knowledge of any framework and tools are handy! At the beginning, I just changed my script ES6 into ES5, and then I searched a lot of knowledge related to packaging. Meanwhile, I was reading the Little Red Book, which made my brain unable to absorb all of a sudden, so I wrote this article to record the remaining pieces of knowledge in my brain. The focus of writing the article is to let oneself scattered knowledge consciously to find the relationship, so as to comb their own, missing o(╥﹏╥) O.
- Modular (
CommonJS
.AMD
.CMD
.UMD
.ES6
.IIFE
) - JavaScript compiler (
bable
) - Packaging tool (
rollup
.webpack
.father
) - Environment (
The node environment
.Browser environment
Compile time
.The runtime
)
This article first combs the modularity.
1. Modular understanding
1. What is modularity?
- Encapsulate a complex program into several blocks (files) according to certain rules (specifications) and combine them together.
- The internal data and implementation of a block are private, exposing only interfaces (methods) to communicate with other external modules.
2. The development history of modularity
- Js didn’t have the concept of modularity until
AJAX
It is proposed that the front end can request data like the back end, the front end logic is more and more complex, there are many problems:Global variables, function name conflicts, and dependencies are hard to handle
. - When using
Self-executing functions (IIFE)
To solve these problems, like the classicjquery
Use anonymous self-executing functions to encapsulate the code and mount it all into global variablesjquery
Here,$(document).ready(function(){}
. - Later, with more and more opportunities for JS to appear, the logical interaction becomes more complex and the functions become more and more, it is necessary to split into multiple files, which leads to one
HTML
Multiple pages need to be loadedscript
Also, there can be naming conflicts, page stuttering due to synchronous loading, and ensuring that the page is loadedjs
Rely on correct. So. - In January 2009,
Node.js
Out of nowhere, it takesCommonJS modular specification
And brought it with himnpm
(the world’s largest module warehouse), followedAMD
,CMD
,UMD
, and now the most popularESM
, are based onJS
The introduction of modular specifications.
AJAX is not a JavaScript specification, it’s just an acronym for “invention” : Asynchronous JavaScript and XML, which means performing Asynchronous web requests in JavaScript. It’s an XMLHttpRequest that gets the data through an onReadyStatechange asynchronous callback to update it. Main problem: Different browsers require different code, and state and error handling can be cumbersome to write. But I thought ajax was a great API for the jquery framework because jquery encapsulates Ajax in such a way that you don’t have to worry about browsers and your code is so much simpler. O (╥ man ╥) o
Ii. Modular specification
1. CommonJS
1) describe
- It is a
Node
In the environmentJS
The modularity specification defines variables, functions, and classes in one file that are private and invisible to other files. - On the server side, modules are loaded synchronously at runtime. On the browser side, modules need to be compiled and packaged in advance.
2) the characteristics of
- All code runs in the module scope and does not pollute the global scope.
- Modules can be loaded multiple times, but only run once on the first load, and then the results are cached and read directly from the cache when they are loaded later. For the module to run again, the cache must be cleared.
- The order in which modules are loaded, in the order they appear in the code.
3) Basic grammar
module.exports = {}
orexports.XX = XX
Import, each file is actually treated as a separate module, and the global scope of each module ismodule
(Modules are not actually global, but local to each module.) .exports
It’s an exported object,Require (" file path ")
Import modules.
// a.js
let value = "a";
let add = () = > {
return value + 1
}
module.exports = {value, add}
// or
// exports.value = value
// exports.add = add
Copy the code
// main.js
const a = require(./a.js) //./ is the relative path
const test = a.add();
console.log(test) // "a" + 1 = "a1"
console.log(a.value) // "a"
Copy the code
4) Loading mechanism
CommonJS
The loading mechanism of a module is that input is a copy of the output value. That is, once a value is output, changes within the module do not affect that value (working principle).require
Is loaded sequentially and synchronously, and at runtime.
5) Caching mechanism
- Modules are cached after the first load. This means that (like other caches) every call
require('foo')
All return exactly the same object (if resolved to the same file). - ifrequire.cacheIf it is not modified, it is called multiple times
require('foo')
Does not cause module code to be executed more than once.
6) run
- Node environments can be loaded and run synchronously
- The browser environment is compiled and run with the help of a packaging tool
2. AMD
1) describe
AMD
Is”Asynchronous Module Definition
“Short for” which means”Asynchronous module definition
“. It loads modules asynchronously without affecting the execution of subsequent statements. All statements that depend on this module are defined in a callback function that will not run until the load is complete.
2) the characteristics of
- Asynchronously load dependencies, preloading all dependencies.
- Using the require.js library, go to the official website to download and import the project.
3) Basic grammar
- with
require.config()
To specify a reference path, etcdefine()
Define a module withrequire()
Load the module.
/** 网页中引入require.js及main.js **/
<script src="js/require.js" data-main="js/main"></script>
// main.js entry file/main module
// First specify the module path and reference name with config()
require.config({
baseUrl: "js/lib".paths: {
"jquery": "jquery.min".// The actual path is js/lib/jquery.min.js
"underscore": "underscore.min",}});// Perform basic operations
require(["jquery"."underscore"].function($, _){
// some code here
});
Copy the code
- Self-defined modules
// math.js
// If additional dependencies need to be introduced, the first argument is [" dependency name "]
define(function () {
var basicNum = 0;
var add = function (x, y) {
return x + y;
};
return {
add: add,
basicNum :basicNum
};
});
// main.js
require(['jquery'.'math'].function($, math){
var sum = math.add(10.20);
$("#sum").html(sum);
});
Copy the code
3. CMD
1) describe
CMD
Is another modular solution that works withAMD
Very similar, the difference is:AMD
To promoteDepending on front-loading and front-loading execution, CMD advocates relying on nearby and delayed execution. This specification is actually in thesea.js
In the process of promotion.CMD
specificationSpecifically used for the browser side, the module load is asynchronous, the module will be loaded and executed when it is used.CMD
The specification integratesCommonJS
andAMD
Specification characteristics. inSea.js
In which allJavaScript
Modules followCMD
Module definition specification.
2) the characteristics of
CMD
The specification is designed specifically for the browser side, where modules are loaded asynchronously and executed only when they are in use.- To integrate the
CommonJS
andAMD
Specification characteristics. - Use the sea-.js library and download it from the official website
3) Basic grammar
// module1.js
define(function(require.exports.module) {
module.exports = {
msg: 'I Will Back'}})/ / the main js file
define(function (require) {
var m1 = require('./module1')})Copy the code
// import sea-.js and import files into HTML
<script type="text/javascript" src="js/libs/sea.js"></script>
<script type="text/javascript">
seajs.use('./js/modules/main')
</script>
Copy the code
4. UMD
1) describe
UMD (Universal Module Definition)
, hoping to provide a back-end cross-platform solution (supportedAMD
withCommonJS
Module mode),.
2) Implementation principle
- Check whether support is supported
Node.js
Module format (exports
If yes, useNode.js
Module format. - Then decide whether to support it
AMD
(define
If yes, useAMD
Mode to load modules. - If neither exists, expose the module globally (
window
orglobal
(That’s rightIIFE
Execute the function immediately. UMD
thegithub
The source code (jQuery
Use)
// Here is simplified code without module dependencies
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// The current environment has define method, use AMD specification.
define([], factory);
} else if (typeof exports= = ='object') {
// Node environment.
module.exports = factory();
} else {
// Browser globals (root is window)
root.returnExports = factory();
}
}(this.function () {
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
return {};
}));
Copy the code
5. ES6 Module
1) describe
- in
ES6
Previously, modularity was implemented usingRequireJS
orseaJS
(Respectively are based onAMD
Specification of modular libraries and based onCMD
Canonical modular library). ES6
Modularity was introduced, with the idea that module dependencies, as well as input and output variables, could be determined at compile time.
2) the characteristics of
- It is loaded at compile time and generated during the code’s static parsing phase.
ES6
The module automatically startsStrict modeWhether or not you add it to the module headeruse strict
;- Each module has its own context, and variables declared in each module are local variables that do not pollute the global scope.
- Each module is loaded only once (singleton). If you load the same file in the same directory again, it is directly read from memory.
3) Basic grammar
export
Commands can appear anywhere in the module, but must be at the top of the module.import
Commands are promoted to the top of the module and executed first.
// export1.js
const addV = (v) = > {
return v + value
}
export const value = 123
export default addV
Copy the code
// rename as
import addV as anything, {value} from "./export1"
console.log(value) / / 123;
console.log(anything(1)) / / 124;
Copy the code
3. To summarize
CommonJS
The server sideandThe browserYou can use either,The server sideisDynamic synchronous loading
The module,The browserYou will need toCompile the package
To introduce again.AMD
andCMD
Are dedicated to the browser side, dynamic asynchronous loading modules, respectively need to be introducedRequire.js
andSea.js
.UMD
Is compatible withCommonJS
andAMD
, as well asIIFE
Package format.ES6
It works on both the server side and the browser side- in
node
Environment useES6 modular specification
There are two ways to change the suffix.mjs
Or in thepackage.json
addtype: module
. - Use in the browser to compile the package import with the packaging tool.
- in
In the next article, I will summarize the packaging tools I have used and be better.