search
HomeWeb Front-endJS TutorialJavaScript modular programming specifications CommonJS, AMD, CMD, ES6

This article brings you relevant knowledge about javascript, which mainly introduces modular programming specifications, CommonJS, AMD, CMD and ES6 related issues. I hope it will be helpful to everyone.

JavaScript modular programming specifications CommonJS, AMD, CMD, ES6

Related recommendations: javascript learning tutorial

1. Foreword

AMD, CMD and CommonJs are modular programming solutions provided in ES5, and import/export is a new modular programming solution provided in ES6.

So, what exactly is AMD, CMD, CommonJs? What are the differences between them? Which modular programming specification should be used for project development, and how to use it? This blog post will answer the above questions one by one.

2. AMD-Asynchronous Module Definition

AMD is the abbreviation of "Asynchronous Module Definition", that is, "Asynchronous Module Definition". It loads modules asynchronously, and the loading of the module does not affect the execution of subsequent statements.

Asynchronous here refers to not blocking other tasks of the browser (dom building, cssrendering, etc.), while loading is internally synchronous (immediately after loading the module execution callback).

RequireJS: It is a AMD framework that can load JS files asynchronously, according to the module loading method, through the define() function Definition, the first parameter is an array, which defines some dependent packages, the second parameter is a callback function, which refers to the methods in the module through variables, and finally outputs through return.

AMD is the standardized output of module definition in RequireJS during the promotion process. It is a concept, RequireJS is the The implementation of this concept is just like the JavaScript language is the implementation of the ECMAScript specification. AMD is an organization, RequireJS is a set of scripting languages ​​customized under this organization.

Different from CommonJS, it requires two parameters:

require([module], callback);

The first parameter[module] is an array with the members is the module to be loaded, callback is the callback function after loading is completed. If the above code is changed to the AMD method:

require(['math'], function(math) {
  math.add(2, 3);})

Among them, the parameters in the callback function correspond to the members (modules) in the array.

requireJSLoading module adopts the AMD specification. In other words, the module must be written in the manner specified by AMD.

Specifically, module writing must be defined using a specific define() function. If a module does not depend on other modules, it can be written directly in the define() function.

define(id, dependencies, factory);
  • id: The name of the module. If this parameter is not provided, the module name should default to the specified script name requested by the module loader;
  • dependencies: Module dependencies, array literals of module identifiers that have been defined by the module. The dependency parameter is optional, if this parameter is omitted it should default to ["require", "exports", "module"]. However, if the factory method's length attribute is less than 3, the loader will choose to call the factory method with the number of arguments specified by the function's length attribute.
  • factory: Factory function of the module, the function or object to be executed during module initialization. If it is a function, it should be executed only once. If it is an object, this object should be the output value of the module.

Assume that there is now a math.js file that defines a math module. Then, math.js is written as follows:

// math.jsdefine(function() {
  var add = function(x, y) {
    return x + y;
  }

  return  {
    add: add  }})

The loading method is as follows:

// main.jsrequire(['math'], function(math) {
  alert(math.add(1, 1));})

If the math module also depends on other modules, it is written as follows:

// math.jsdefine(['dependenceModule'], function(dependenceModule) {
    // ...})

When the require() function loads the math module, the dependenceModule module will be loaded first. When there are multiple dependencies, all dependencies are written in the first parameter array of the define() function, so AMD is pre-dependent. This is different from the CMD specification, which relies on proximity.
CMD

3. CMD-synchronization module definition

CMD is Common Module Definitioncommon module definition, which is SeaJSThe standardized output of module definition during the promotion process is a synchronized module definition, which is a standard of SeaJS, SeaJS is a concept of CMD Implementation, SeaJS is a module development js framework provided by Taobao team Yubo. CMDThe specification is developed domestically, just like AMD has requireJS, CMD has a browser implementationSeaJS , SeaJS The problem to be solved is the same as requireJS, but it is different in the module definition method and module loading (it can be said to run, parse) timing.

CMD 通过define()定义,没有依赖前置,通过require加载jQuery插件,CMD是依赖就近,在什么地方使用到插件就在什么地方require该插件,即用即返,这是一个同步的概念。

CMD 规范中,一个模块就是一个文件。代码的书写格式如下:

define(function(require, exports, module) {
  // 模块代码});

其中,

  • require是可以把其他模块导入进来的一个参数;
  • exports是可以把模块内的一些属性和方法导出的;
  • module 是一个对象,上面存储了与当前模块相关联的一些属性和方法。

AMD是依赖关系前置,在定义模块的时候就要声明其依赖的模块;
CMD是按需加载依赖就近,只有在用到某个模块的时候再去require,示例代码如下:

// CMDdefine(function(require, exports, module) {
  var a = require('./a')
  a.doSomething()
  // 此处略去 100 行
  var b = require('./b') // 依赖可以就近书写
  b.doSomething()
  // ... })// AMD 默认推荐的是define(['./a', './b'], function(a, b) { // 依赖必须一开始就写好
  a.doSomething()
  // 此处略去 100 行
  b.doSomething()
  ...})

四、CommonJS 规范

CommonJS规范是通过module.exports定义的,在前端浏览器里面并不支持module.exports,通过node.js后端使用。Nodejs端使用CommonJS规范,前端浏览器一般使用AMDCMDES6等定义模块化开发规范。

CommonJS的终极目标是提供一个类似PythonRubyJava的标准库。这样的话,开发者可以使用CommonJS API编写应用程序,然后这些应用就可以运行在不同的JavaScript解释器和不同的主机环境中。

在兼容CommonJS的系统中,你可以使用JavaScript开发以下程序:

  1. 服务器端JavaScript应用程序;
  2. 命令行工具;
  3. 图形界面应用程序;
  4. 混合应用程序(如,Titanium或Adobe AIR);

2009年,美国程序员Ryan Dahl创造了node.js项目,将javascript语言用于服务器端编程。这标志"Javascript模块化编程"正式诞生。NodeJSCommonJS规范的实现,webpack 也是以CommonJS的形式来书写。

node.js的模块系统,就是参照CommonJS规范实现的。在CommonJS中,有一个全局性方法require(),用于加载模块。假定有一个数学模块math.js,就可以像下面这样加载。

var math = require('math');

然后,就可以调用模块提供的方法:

var math = require('math');math.add(2,3); // 5

CommonJS定义的模块分为:模块引用(require)模块定义(exports)模块标识(module)
其中,

  • require()用来引入外部模块;
  • exports对象用于导出当前模块的方法或变量,唯一的导出口;
  • module对象就代表模块本身。

虽说NodeJS遵循CommonJS的规范,但是相比也是做了一些取舍,添了一些新东西的。

NPM作为Node包管理器,同样遵循CommonJS规范。

下面讲讲commonJS的原理以及简易实现:

1、原理
浏览器不兼容CommonJS的根本原因,在于缺少四个Node.js环境变量。

module
exports
require
global

只要能够提供这四个变量,浏览器就能加载 CommonJS 模块。

下面是一个简单的示例。

var module = {
  exports: {}};(function(module, exports) {
  exports.multiply = function (n) { return n * 1000 };
  }(module, module.exports))var f = module.exports.multiply;
  f(5) // 5000

上面代码向一个立即执行函数提供 module 和 exports 两个外部变量,模块就放在这个立即执行函数里面。模块的输出值放在 module.exports 之中,这样就实现了模块的加载。

2、Browserify 的实现
Browserify 是目前最常用的 CommonJS 格式转换工具。

请看一个例子,main.js 模块加载 foo.js 模块。

// foo.jsmodule.exports = function(x) {
  console.log(x);};// main.jsvar foo = require("./foo");foo("Hi");

使用下面的命令,就能将main.js转为浏览器可用的格式。

$ browserify main.js > compiled.js

其中,Browserify到底做了什么?安装一下browser-unpack,就清楚了。

$ npm install browser-unpack -g

然后,将前面生成的compile.js解包。

$ browser-unpack <pre class="brush:php;toolbar:false">[
  {
    "id":1,
    "source":"module.exports = function(x) {\n  console.log(x);\n};",
    "deps":{}
  },
  {
    "id":2,
    "source":"var foo = require(\"./foo\");\nfoo(\"Hi\");",
    "deps":{"./foo":1},
    "entry":true
  }]

可以看到,browerify 将所有模块放入一个数组,id 属性是模块的编号,source 属性是模块的源码,deps 属性是模块的依赖。

因为 main.js 里面加载了 foo.js,所以 deps 属性就指定 ./foo 对应1号模块。执行的时候,浏览器遇到 require('./foo') 语句,就自动执行1号模块的 source 属性,并将执行后的 module.exports 属性值输出。

五、ES6

有关es6模块特性,强烈推荐阮一峰老师的:ECMAScript 6 入门 - Module 的语法专栏。

要说 ES6 模块特性,那么就先说说 ES6 模块跟 CommonJS 模块的不同之处。

  • ES6 模块输出的是值的引用,输出接口动态绑定,而 CommonJS 输出的是值的拷贝;
  • ES6 模块编译时执行,而 CommonJS 模块总是在运行时加载。

CommonJS 模块输出的是值的拷贝(原始值的拷贝),也就是说,一旦输出一个值,模块内部的变化就影响不到这个值。

// a.jsvar b = require('./b');console.log(b.foo);setTimeout(() => {
  console.log(b.foo);
  console.log(require('./b').foo);}, 1000);// b.jslet foo = 1;setTimeout(() => {
  foo = 2;}, 500);module.exports = {
  foo: foo,};// 执行:node a.js// 执行结果:// 1// 1// 1

上面代码说明,b 模块加载以后,它的内部 foo 变化就影响不到输出的 exports.foo 了。这是因为 foo 是一个原始类型的值,会被缓存。所以如果你想要在 CommonJS 中动态获取模块中的值,那么就需要借助于函数延时执行的特性。

// a.jsvar b = require('./b');console.log(b.foo);setTimeout(() => {
  console.log(b.foo);
  console.log(require('./b').foo);}, 1000);// b.jsmodule.exports.foo = 1;   // 同 exports.foo = 1 setTimeout(() => {
  module.exports.foo = 2;}, 500);// 执行:node a.js// 执行结果:// 1// 2// 2

所以我们可以总结一下:

  • CommonJS 模块重复引入的模块并不会重复执行,再次获取模块直接获得暴露的module.exports 对象。
  • 如果你需要处处获取到模块内的最新值的话,也可以每次更新数据的时候每次都要去更新 module.exports 上的值
  • 如果暴露的 module.exports 的属性是个对象,那就不存在这个问题了。

相关推荐:javascript视频教程

The above is the detailed content of JavaScript modular programming specifications CommonJS, AMD, CMD, ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

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 Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

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.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.