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 untilAJAXIt 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 usingSelf-executing functions (IIFE)To solve these problems, like the classicjqueryUse anonymous self-executing functions to encapsulate the code and mount it all into global variablesjqueryHere,$(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 oneHTMLMultiple pages need to be loadedscriptAlso, there can be naming conflicts, page stuttering due to synchronous loading, and ensuring that the page is loadedjsRely on correct. So.
  • In January 2009,Node.jsOut of nowhere, it takesCommonJS modular specificationAnd brought it with himnpm(the world’s largest module warehouse), followedAMD,CMD,UMD, and now the most popularESM, are based onJSThe 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 aNodeIn the environmentJSThe 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 = XXImport, 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.) .exportsIt’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

  • CommonJSThe 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).requireIs loaded sequentially and synchronously, and at runtime.

5) Caching mechanism

  • Modules are cached after the first load. This means that (like other caches) every callrequire('foo')All return exactly the same object (if resolved to the same file).
  • ifrequire.cacheIf it is not modified, it is called multiple timesrequire('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

  • AMDIs”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

  • withrequire.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

  • CMDIs another modular solution that works withAMDVery similar, the difference is:AMDTo promoteDepending on front-loading and front-loading execution, CMD advocates relying on nearby and delayed execution. This specification is actually in thesea.jsIn the process of promotion.
  • CMDspecificationSpecifically used for the browser side, the module load is asynchronous, the module will be loaded and executed when it is used.CMDThe specification integratesCommonJSandAMDSpecification characteristics. inSea.jsIn which allJavaScriptModules followCMDModule definition specification.

2) the characteristics of

  • CMDThe specification is designed specifically for the browser side, where modules are loaded asynchronously and executed only when they are in use.
  • To integrate theCommonJSandAMDSpecification 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 (supportedAMDwithCommonJSModule mode),.

2) Implementation principle

  • Check whether support is supportedNode.jsModule format (exportsIf yes, useNode.jsModule format.
  • Then decide whether to support itAMD(defineIf yes, useAMDMode to load modules.
  • If neither exists, expose the module globally (windoworglobal(That’s rightIIFEExecute the function immediately.
  • UMDthegithubThe source code (jQueryUse)
// 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

  • inES6Previously, modularity was implemented usingRequireJSorseaJS(Respectively are based onAMDSpecification of modular libraries and based onCMDCanonical modular library).
  • ES6Modularity 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.
  • ES6The 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

  • exportCommands can appear anywhere in the module, but must be at the top of the module.
  • importCommands 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

  • CommonJSThe server sideandThe browserYou can use either,The server sideisDynamic synchronous loadingThe module,The browserYou will need toCompile the packageTo introduce again.
  • AMDandCMDAre dedicated to the browser side, dynamic asynchronous loading modules, respectively need to be introducedRequire.jsandSea.js.
  • UMDIs compatible withCommonJSandAMD, as well asIIFEPackage format.
  • ES6It works on both the server side and the browser side
    • innodeEnvironment useES6 modular specificationThere are two ways to change the suffix.mjsOr in thepackage.jsonaddtype: module.
    • Use in the browser to compile the package import with the packaging tool.

In the next article, I will summarize the packaging tools I have used and be better.