在最开始JavaScript没有import / export模块这些机制。所有的代码都在一个文件里,这几乎就是劫难。

之后就呈现了一些机制扭转只有一个文件的问题。于是就呈现了CJS、AMD、UMD和ESM。这篇小文就是让大家理解这些都是什么。

CJS

CJS全称CommonJS。看起来是这样的:

//importing const doSomething = require('./doSomething.js'); //exportingmodule.exports = function doSomething(n) {  // do something}

CJS常常在node开发中呈现。

  • CJS应用同步形式引入模块
  • 你能够从node_modules或者本地目录引入模块。如:const someModule = require('./some/local/file');
  • CJS引入模块的一个复制文件。
  • CJS不能在浏览器里工作。要在浏览器里应用,则须要转码和打包

AMD

AMD的全称是异步模块定义。如:

define(['dep1', 'dep2'], function (dep1, dep2) {    //Define the module value by returning a value.    return function () {};});

或者

// "simplified CommonJS wrapping" https://requirejs.org/docs/whyamd.htmldefine(function (require) {    var dep1 = require('dep1'),        dep2 = require('dep2');    return function () {};});
  • AMD异步引入模块,也是因而得名
  • ADM是给前端用的
  • AMD不如CJS直观

UMD

UMD全称是Universal Module Definition。如:

(function (root, factory) {    if (typeof define === "function" && define.amd) {        define(["jquery", "underscore"], factory);    } else if (typeof exports === "object") {        module.exports = factory(require("jquery"), require("underscore"));    } else {        root.Requester = factory(root.$, root._);    }}(this, function ($, _) {    // this is where I defined my module implementation    var Requester = { // ... };    return Requester;}));
  • 能够在前端和后端通用
  • 与CJS和AMD不同,UMD更像是配置多模块零碎的模式
  • UMD通常是Rollup、webpack的候补抉择

ESM

ESM的全称是ES Modules。如:

import React from 'react';

或者

import {foo, bar} from './myLib';...export default function() {  // your Function};export const function1() {...};export const function2() {...};
  • 在很多古代的浏览器里都能够用
  • 前后端都能够用。CJS一样的简略的语法规定和AMD异步摇树
  • ESM容许打包工具,比方Rollup、webpack去除不必要的代码
  • 在HTML调用

    <script type="module">import {func1} from 'my-lib';func1();</script>

临时还没有失去全副浏览器的反对。

总结

  • ESM得益于简略的语法、异步和摇树的特点,基本上就是最好的模块机制了
  • UMD哪里都能够用,所以被用作备用打包计划
  • CJS是同步的,在后端中用的比拟多
  • AMD是异步的,对前端敌对

感激浏览!