Examples of modular understanding in Javascript
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('result').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('result').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<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:php;toolbar:false;'>---------------- 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);</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:php;toolbar:false;'> sum = require(&#39;./sum&#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:php;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:php;toolbar:false;'>-------------------- 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; });</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:php;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:php;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('./add'); module.exports = function sum(n){ return add(1, 2) + n; } ---------------- main.js -------------------- var sum = require('./sum'); document.getElementById('result').innerHTML = sum(3); 命令: browserify main.js -o bundle.js
Confused times: UMD
// UMD 风格编写的 sum 模块 //sum.umd.js (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['add'], factory); } else if (typeof exports === 'object') { // Node, CommonJS-like module.exports = factory(require('add')); } 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; } }));
The bright era: ES6 module syntax
ES6 uses theimport and
export keywords To import and export modules
---------------- main.js --------------- import sum from './sum'; document.getElementById('result').innerHTML = sum(3); ---------------- sum.js --------------- import add from './add'; export default function sum(n){ return add(1, 2) + n; }; ---------------- add.js --------------- export default function add(a, b){ return a + b; };
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 './add'; export default (n) => {return add(1, 2) + n}; --------------- main.js ---------------- import sum from './sum'; document.getElementById('result').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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
