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

Examples of modular understanding in Javascript

黄舟
Release: 2017-10-31 09:42:34
Original
1553 people have browsed it

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);
Copy after login

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);
Copy after login

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

<script><code> tags in a server application, it makes sense to provide some clear API for modules. Modules need to be exposed (</code>**export**<code>) for use by other modules and accessible (</code>**import**<code>). Its export module syntax is as follows: </code><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">---------------- add.js -------------------- module.exports = function add(a, b){ return a+b; } ---------------- sum.js -------------------- var add = require(&amp;#39;./add&amp;#39;); module.exports = function sum(n){ return add(1, 2) + n; } ---------------- main.js -------------------- var sum = require(&amp;#39;./sum&amp;#39;); document.getElementById(&amp;#39;result&amp;#39;).innerHTML = sum(3);</pre><div class="contentsignin">Copy after login</div></div></p> Although CommonJs solves the dependency problem, the problem with CommonJs is that it is synchronous, when var sum = require('./sum'); <p> <span style="color: #0000ff"> </span><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;"> sum = require(&amp;#39;./sum&amp;#39;);时,系统将暂停,直到模块准备(ready)完成,这意味着当所有的模块都加载时,这一行代码将阻塞浏览器进程, 因此,这可能不是为浏览器端应用程序定义模块的最佳方式</pre><div class="contentsignin">Copy after login</div></div></p><p><strong>Asynchronous Module Era<strong>: AMD</strong></strong><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">define([‘add’, ‘sum’], function(add, sum){ document.getElementById.innerHTML = sum(3); });</pre><div class="contentsignin">Copy after login</div></div></p><p>define<code> Function (or keyword) combines the dependency list with </code>Callback function<a href="http://www.php.cn/code/8530.html" target="_blank"> as parameters. The parameters of the callback </a> function <a href="http://www.php.cn/code/64.html" target="_blank"> 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. </a></p>CommonJS and AMD solve the two remaining problems in the module pattern: <p>Dependency resolution<strong> and </strong>Global scope pollution<strong>. We only need to deal with the dependencies of each module or each file, and weapons no longer have global scope pollution. </strong><br/></p><p><strong>Good implementation of AMD: RequireJS <strong><strong><strong>Dependency Injection<a href="http://www.php.cn/php/php-tp-unity.html" target="_blank"></a></strong></strong></strong></strong> </p>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. <p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">-------------------- html ---------------------- &lt;p id=&quot;result&quot;&gt;&lt;/p&gt; &lt;!-- 入口文件 --&gt; &lt;script data-main=&quot;main&quot; src=&quot;require.js&quot;&gt;&lt;/script&gt; -------------------- main.js ---------------------- define([&amp;#39;sum&amp;#39;], function(sum){ document.getElementById(&amp;#39;result&amp;#39;).innerHTML = sum(3); }) -------------------- sum.js ---------------------- define([&amp;#39;add&amp;#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; });</pre><div class="contentsignin">Copy after login</div></div></p>The browser loads <p>index.html<code>, and </code>index.html<code> loads </code>require.js<code>. The remaining files and their dependencies are loaded by </code>require.js<code>. </code></p>RequireJS and AMD solve all the problems we had before. However, it also brings some less serious problems: <p></p>1. AMD's syntax is too redundant. Because everything is encapsulated in a <p>define<code> function</code></p>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<p></p>3. Under current browsers (HTTP 1.1), loading many small files will reduce performance<p></p><p><strong>Module packager: <strong>Browserify</strong></strong></p><p>You can use CommonJS modules in the browser, traverse the dependency tree of the code through <span style="line-height: 1.5"></span>Browserify, and add the dependencies in the dependency tree to All modules are packaged into one file. <span style="line-height: 1.5"></span></p>Different from RequireJS, Browserify is a command line tool that needs to rely on the NPM environment. <p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">npm install -g browserify</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">---------------- html.js -------------------- <p id="result"></p> <!-- 打包好的文件 --> <script src="boundle.js"></script> ---------------- 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

Copy after login

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;
    }
}));
Copy after login

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;
};
Copy after login

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);
Copy after login

发现 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template