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 (**export**<code>) for use by other modules and accessible (**import**<code>). Its export module syntax is as follows: <pre class='brush:php;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></script></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><pre class='brush:php;toolbar:false;'> sum = require(&amp;#39;./sum&amp;#39;);时,系统将暂停,直到模块准备(ready)完成,这意味着当所有的模块都加载时,这一行代码将阻塞浏览器进程, 因此,这可能不是为浏览器端应用程序定义模块的最佳方式</pre></p> <p><strong>Asynchronous Module Era<strong>: AMD</strong></strong><pre class='brush:php;toolbar:false;'>define([‘add’, ‘sum’], function(add, sum){ document.getElementById.innerHTML = sum(3); });</pre></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><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></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><pre class='brush:php;toolbar:false;'>npm install -g browserify</pre><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; } }));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 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; };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 './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!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment