Home  >  Article  >  Web Front-end  >  Examples of modular understanding in Javascript

Examples of modular understanding in Javascript

黄舟
黄舟Original
2017-10-31 09:42:341487browse

Original era: The script tag introduces javascriptfiles

-------- html -------
<p id="result"></p>
<script type="text/javascript" src="add.js"></script>
<script type="text/javascript" src="sum.js"></script>
<script type="text/javascript" src="main.js"></script>
-------add.js------
function add(a, b){ return a + b ;}
------ sum.js -----
function sum(n){
   return n + add(1, 2);
}
----- main.js ----
document.getElementById(&#39;result&#39;).innerHTML = sum(3);

This method lacks dependency analysis, pollutes the global variable space, and must ensure the order in which files are introduced. Management is confusing

Original era: Module objects and IIFE patterns

By using module objects and immediately called function expressions(IIFE), We can reduce pollution of the global scope. In this approach, we only expose an object to the global scope. This object contains all the methods and values ​​we need in our application.

例如只向全局作用域公开了 App 对象
-------- html -------
<p id="result"></p>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="add.js"></script>
<script type="text/javascript" src="sum.js"></script>
<script type="text/javascript" src="main.js"></script>
------- app.js -------
var App = {};
------- add.js -------
(function(){
    App.add = function(a, b){
       return a + b;
   }
})();
------- sum.js -------
(function(){
    App.sum= function(n){
       return App.add(1, 2) + n;
   }
})();
------- main.js -------
(function(app){
   document.getElementById(&#39;result&#39;).innerHTML = app.sum(3);
})(App);

You can see that except app.js, every other file is encapsulated into IIFE format

There is still a lack of dependency parsing problem, there is still 1 global variable, and Instead of getting rid of all global variables

Transition Era: CommonJS

##CommonJS is not a JavaScript library. It is a standards organization. It's like ECMA or W3C. ECMA defines the JavaScript language specification. W3C defines JavaScript web APIs such as DOM or DOM events. The goal of CommonJS is to define a common set of APIs for web servers, desktops, and command line applications.

CommonJS also defines a module API. Since there are no HTML pages and

2cacc6d41bbb37262a98f745aa00fbf03f1c4e4b6b16bbbd69b2ee476dc4f83a tags in a server application, it makes sense to provide some clear API for modules. Modules need to be exposed (**export**) for use by other modules and accessible (**import**). Its export module syntax is as follows:

---------------- add.js  --------------------
module.exports = function add(a, b){
  return a+b;
}
---------------- sum.js  --------------------
var add = require(&#39;./add&#39;);
module.exports  = function sum(n){
     return add(1, 2) + n;
}
---------------- main.js  --------------------
var sum = require(&#39;./sum&#39;);
document.getElementById(&#39;result&#39;).innerHTML = sum(3);

Although CommonJs solves the dependency problem, the problem with CommonJs is that it is synchronous, when var sum = require('./sum');

 sum = require(&#39;./sum&#39;);时,系统将暂停,直到模块准备(ready)完成,这意味着当所有的模块都加载时,这一行代码将阻塞浏览器进程,
因此,这可能不是为浏览器端应用程序定义模块的最佳方式

Asynchronous Module Era: AMD

define([‘add’, ‘sum’], function(add, sum){
  document.getElementById.innerHTML = sum(3);
});

define Function (or keyword) combines the dependency list with Callback function as parameters. The parameters of the callback function are in the same order as the dependencies in the array. This is equivalent to importing a module. And the callback function returns a value, which is the value you exported.

CommonJS and AMD solve the two remaining problems in the module pattern:

Dependency resolution and Global scope pollution. We only need to deal with the dependencies of each module or each file, and weapons no longer have global scope pollution.

Good implementation of AMD: RequireJS Dependency Injection

RequireJS is a JavaScript module loader. It can load modules asynchronously as needed. Although RequireJS contains require in its name, its goal is not to support CommonJS's require syntax. Using RequireJS, you can write AMD-style modules.

-------------------- html ----------------------
<p id="result"></p>
<!-- 入口文件 -->
<script data-main="main" src="require.js"></script>
-------------------- main.js ----------------------
define([&#39;sum&#39;], function(sum){
  document.getElementById(&#39;result&#39;).innerHTML = sum(3);
})
-------------------- sum.js ----------------------
define([&#39;add&#39;], function(add)){
   var sum = function(n){
       return add(1,2) + n;
   }
   return sum;
})
-------------------- add.js ----------------------
// add.js
define([], function(){
   var add = function(a, b){
      return a + b;
   };
   return add;
});

The browser loads

index.html, and index.html loads require.js. The remaining files and their dependencies are loaded by require.js.

RequireJS and AMD solve all the problems we had before. However, it also brings some less serious problems:

1. AMD's syntax is too redundant. Because everything is encapsulated in a

define function

2. The dependency list in the array must match the parameter list of the function. If there are many dependencies, it is difficult to maintain the order of dependencies

3. Under current browsers (HTTP 1.1), loading many small files will reduce performance

Module packager: Browserify

You can use CommonJS modules in the browser, traverse the dependency tree of the code through Browserify, and add the dependencies in the dependency tree to All modules are packaged into one file.

Different from RequireJS, Browserify is a command line tool that needs to rely on the NPM environment.

npm install -g browserify
---------------- html.js  --------------------

---------------- add.js -------------------- module.exports = function add(a, b){ return a+b; } ---------------- sum.js -------------------- var add = require(&#39;./add&#39;); module.exports = function sum(n){ return add(1, 2) + n; } ---------------- main.js -------------------- var sum = require(&#39;./sum&#39;); document.getElementById(&#39;result&#39;).innerHTML = sum(3); 命令: browserify main.js -o bundle.js

Confused times: UMD

UMD is a set of if/else statements used to identify the module style supported by the current environment

// UMD 风格编写的 sum 模块
//sum.umd.js
(function (root, factory) {
    if (typeof define === &#39;function&#39; && define.amd) {
        // AMD
        define([&#39;add&#39;], factory);
    } else if (typeof exports === &#39;object&#39;) {
        // Node, CommonJS-like
        module.exports = factory(require(&#39;add&#39;));
    } else {
        // Browser globals (root is window)
        root.sum = factory(root.add);
    }
}(this, function (add) {
    //  private methods
    //  exposed public methods
    return function(n) {
      return add(1,2) + n;
    }
}));

Whether it is JavaScript global module object, CommonJS or AMD or even UMD, it is too It's troublesome, it adds a lot of extra work, and it's not easy to maintain.

The bright era: ES6 module syntax

ES6 uses the

import and export keywords To import and export modules

---------------- main.js ---------------
import sum from &#39;./sum&#39;;
document.getElementById(&#39;result&#39;).innerHTML = sum(3);
---------------- sum.js ---------------
import add from &#39;./add&#39;;
export default function sum(n){
   return  add(1, 2) + n;
};
---------------- add.js ---------------
export default function add(a, b){
   return a + b;
};

ES6 module syntax is concise. Although not all browsers currently support it, you can use some tools (babel) to convert it

The era of engineering: Webpack

虽然gulp、grunt都号称是工程化开发工具,,但个人感觉他们处理的东西还是比较基础,对于模块依赖打包来说,支持不是非常好,反正我是不喜欢gulp.

Webpack 是一个 模块打包器,就像 Browserify 一样,它会遍历依赖树,然后将其打包到一到多个文件。

它与Browserify 不同之处就是 可以处理 CommonJS 、 AMD 和 ES6 模块,并且 Webpack 还有更多实用的东西,比如 代码分离、加载器、插件

简洁的时代:Rollup

rollup 只会将需要的函数包含到打包文件中,从而显著减少打包文件大小

--------------- add.js -----------------
let add = (a,b) => a + b;
let sub = (a,b) => a - b;
export { add, sub };
--------------- sum.js -----------------
import { add } from &#39;./add&#39;;
export default (n) => {return add(1, 2) + n};
--------------- main.js ----------------
import sum from &#39;./sum&#39;;
document.getElementById(&#39;result&#39;).innerHTML = sum(3);

命令: rollup main.js -o bundle.js
--------------- boundle.js ----------------
// bundle.js
let add = (a,b) => a + b;
var sum = (n) => {return add(1, 2) + n};
document.getElementById("answer").innerHTML = sum(3);

发现 add.js的 sub() 函数并没有包含在这个打包文件中,因为没有引用它。

The above is the detailed content of Examples of modular understanding in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn