【译】一次性理解CJS, AMD, UMD, ESM, System, IIFE 分别代表什么

Hello大家好,我是不浪,坚持从工作和生活中不断学习,提炼,沉淀,最终建立自己的强势领域!这是2024年输出的第1/100篇文章,欢迎志同道合的朋友一起学习交流,微信:brown_7778"

最近在工作中需要开发一个JS封装Unreal接口的一个库,所以在考虑这个库需要打包成什么类型的包,这些包都有什么特点,需要如何去加载使用它,身为前端高级工程师或者是架构师,这应该是我们工作中一定会遇到的问题。

现代 Javascript 项目需要用打包工具来将小段代码编译成库或者应用程序那种更大更复杂的东西。流行的打包器有webpackRollupParcelRequireJSBrowserify。它们将 JavaScript 代码转换为可以作为一个 bundle 加载的模块。

一个 bundle 可以用不同的格式打包。这篇文章中,我们将展示 CJS, AMD, UMD, ESM, SystemIIFE 格式的打包示例。

打包工具和格式 下面是一个标准的 HTML 文件,第5行引入了一个样式文件,第6行引入了一个 JS 文件:

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <link rel="stylesheet" href="style.css" />
    <script src="src/index.js"></script>
  </head>
  <body>
    ... 
  </body>
</html>

简单情况下可以将所有的 JavaScript 代码放到一个文件中。随着项目的增大,我们需要将代码拆分成具有独立命名空间的独立模块。除了更好的结构,模块化还带来了封装的功能、依赖管理和复用性。 这就是打包工具出现的原因。它需要将小块的 JavaScript 代码,样式表和图片编译成更大更复杂的像库或者应用程序一样的东西。

打包工具是如何将打包的代码格式化为输出?有很多的选择, 下面是 Rollup 定义的一些格式:

  • cjs (CommonJS) --- 适用于 Node 和其他打包工具(别名:commonjs)。
  • amd (Asynchronous Module Definition,异步模块化定义) --- 与 RequireJS 等模块加载工具一起使用。
  • umd (Universal Module Definition,通用模块化定义) --- amdcjsiife 包含在一个文件中。
  • es --- 将 bundle 保存为 ES 模块文件。适用于其他打包工具,在现代浏览器中用 <script type=module> 标签引入(别名:ems, module)。
  • iife --- <script> 标签引入的自执行函数。如果你想为你的应用创建一个包,你需要用到的可能就是这种。

在这篇文章中,我们将通过示例解释这些格式。

示例

下面是一个打包四个文件的示例:

  • index.js
  • increase.js
  • decrease.js
  • other.js

入口文件是 index.js:

js 复制代码
/**
 * This is the main file
 */
import { increase } from './increase';
import { decrease } from './decrease';
import others, { e } from './others';
function multiply(total, value) {
  return total * value;
}

function divide(total, value) {
  return total / value;
}

export function power(total, value) {
  return total ** value;
}

let total = others.a;

total = increase(total, 10);
total = increase(total, 20);
total = decrease(total, 5);
total = multiply(total, e);

console.log(`Total is ${total}`);

4-6 行中,index.js 明确地列出了从 increase.js,decrease.js 和 other.js 中引入的内容。

这是引入的 increase.js:

js 复制代码
/**
 * Increase the current total value
 * @param {number} total The current total value
 * @param {number} value The new value to be added
 * @returns {number} The new total value
 */
export const increase = (total, value) => total + value;

这是引入的 decrease.js:

js 复制代码
/**
 * Decrease the current total value
 * @param {number} total The current total value
 * @param {number} value The new value to be subtracted
 * @returns {number} The new total value
 */
export const decrease = (total, value) => total - value;

这是引入的 other.js:

js 复制代码
export default {
  a: 1,
  b: 2,
  c: () => 3,
};

export const d = 4;
export const e = 5;

在这个示例中, other.js 中的 const d 和 index.js 中的 function divide() 未被使用。index.js 中的 function power() 虽然也未用到但被导出了。

ES2015/ES6 引入了静态 import 和 export,允许静态分析器在不运行代码的情况下构建完整的依赖关系树。此外,这为 tree shaking(摇树)优化奠定了基础。根据维基百科:

Tree shaking 从入口开始,只包含可能被执行的函数,删除包中未使用的函数。

因为这个示例是用 ES2015 编写的,且带有特定的导入(不是 import *),所以摇树过程会删除所有生成格式中的 const d 和 function divide()。因为导出的函数可能会被使用,function power() 得以保留。

CommonJS(CJS)


CJS 适用于浏览器之外的 Node 和其他生态系统。它在服务端被广泛使用。CJS 可以通过使用 require() 函数和 module.exports 来识别。require() 是一个可用于从另一个模块导入 symbols 到当前作用域的函数。 module.exports 是当前模块在另一个模块中引入时返回的对象。

CJS 模块的设计考虑到了服务器开发。这个 API 天生是同步的。换言之,在源文件中按 require 的顺序瞬时加载模块。

由于 CJS 是同步的且不能被浏览器识别,CJS 模块不能在浏览器端使用,除非它被转译器打包。像 Babel 和 Traceur 那样的转译器,是一种帮助我们在新版 JavaScript 中编码的工具。如果环境原生不支持新版本的 JavaScript,转译器将它们编译成支持的 JS 版本。 下面是 Rollup 生成的 CJS 格式的文件:

js 复制代码
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

/**
 * Increase the current total value
 * @param {number} total The current total value
 * @param {number} value The new value to be added
 * @returns {number} The new total value
 */
const increase = (total, value) => total + value;

/**
 * Decrease the current total value
 * @param {number} total The current total value
 * @param {number} value The new value to be subtracted
 * @returns {number} The new total value
 */
const decrease = (total, value) => total - value;

var others = {
  a: 1,
  b: 2,
  c: () => 3,
};
const e = 5;

/**
 * This is the main file
 */

function multiply(total, value) {
  return total * value;
}

function power(total, value) {
  return total ** value;
}

let total = others.a;

total = increase(total, 10);
total = increase(total, 20);
total = decrease(total, 5);
total = multiply(total, e);

console.log(`Total is ${total}`);

exports.power = power;

我们在浏览器端执行这个文件,它会报错,报错信息是 exports is not defined (第3行)。 这个错误可以通过 index.html 中添加以下代码来修复:

js 复制代码
<script>
  const exports = {};
</script>

异步模块定义(AMD)


AMD 脱胎于 CJS,支持异步模块加载。AMDCJS 的主要区别在于它是否支持异步模块加载。RequireJS 使用 AMD 在浏览器端工作。 据 维基百科:

AMD 提供了一些 CJS 相似的特性。它允许在代码中使用类似的 exports 和 require() 接口,尽管它自己的 define() 接口更基础更受欢迎。

下面是 Rollup 生成的 AMD 格式的文件:

js 复制代码
define(['exports'], function (exports) { 'use strict';

  /**
   * Increase the current total value
   * @param {number} total The current total value
   * @param {number} value The new value to be added
   * @returns {number} The new total value
   */
  const increase = (total, value) => total + value;

  /**
   * Decrease the current total value
   * @param {number} total The current total value
   * @param {number} value The new value to be subtracted
   * @returns {number} The new total value
   */
  const decrease = (total, value) => total - value;

  var others = {
    a: 1,
    b: 2,
    c: () => 3,
  };
  const e = 5;

  /**
   * This is the main file
   */
                                        
  function multiply(total, value) {
    return total * value;
  }

  function power(total, value) {
    return total ** value;
  }

  let total = others.a;

  total = increase(total, 10);
  total = increase(total, 20);
  total = decrease(total, 5);
  total = multiply(total, e);

  console.log(`Total is ${total}`);

  exports.power = power;

  Object.defineProperty(exports, '__esModule', { value: true });

});

我们在浏览器上执行这个文件,它会报错,报错信息是 define is not a function (第1行)。 这个报错能通过在 index.html 中引入 require.js 修复。

js 复制代码
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>

通用模块定义(UMD)


UMD 被设计用于任何地方 --- 包括服务端和浏览器端。它试图兼容目前最流行的 script 加载器(如 RequireJS)。在许多情况下,它使用 AMD 作为基础,且兼容 CJS。然而兼容增加了一些复杂度,使得读写变得更加困难。

下面是 Rollup 生成的 UMD 格式的文件:

js 复制代码
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.example = {}));
}(this, (function (exports) { 'use strict';

  /**
   * Increase the current total value
   * @param {number} total The current total value
   * @param {number} value The new value to be added
   * @returns {number} The new total value
   */
  const increase = (total, value) => total + value;

  /**
   * Decrease the current total value
   * @param {number} total The current total value
   * @param {number} value The new value to be subtracted
   * @returns {number} The new total value
   */
  const decrease = (total, value) => total - value;

  var others = {
    a: 1,
    b: 2,
    c: () => 3,
  };
  const e = 5;

  /**
   * This is the main file
   */
                             
  function multiply(total, value) {
    return total * value;
  }

  function power(total, value) {
    return total ** value;
  }

  let total = others.a;

  total = increase(total, 10);
total = increase(total, 20);
  total = decrease(total, 5);
  total = multiply(total, e);

  console.log(`Total is ${total}`);

  exports.power = power;

  Object.defineProperty(exports, '__esModule', { value: true });

})));

此代码可以在浏览器中工作。

ES2015 模块(ESM)


静态 import 指令可用于将模块引入当前作用域。与 require 和 define 不同,这个指令只能放在文件的顶部。动态 import() 目前处于 TC39 流程的第4阶段。

另一方面,export 指令可用于显式地将对象公开。

下面是 Rollup 生成的 ESM 格式的文件:

js 复制代码
/**
 * Increase the current total value
 * @param {number} total The current total value
 * @param {number} value The new value to be added
 * @returns {number} The new total value
 */
const increase = (total, value) => total + value;

/**
 * Decrease the current total value
 * @param {number} total The current total value
 * @param {number} value The new value to be subtracted
 * @returns {number} The new total value
 */
const decrease = (total, value) => total - value;

var others = {
  a: 1,
  b: 2,
  c: () => 3,
};
const e = 5;

/**
 * This is the main file
 */

function multiply(total, value) {
  return total * value;
}

function power(total, value) {
  return total ** value;
}

let total = others.a;

total = increase(total, 10);
total = increase(total, 20);
total = decrease(total, 5);
total = multiply(total, e);

console.log(`Total is ${total}`);

export { power };

我们在浏览器上运行这个文件,它会报错,报错信息是 Uncaught SyntaxError: Unexpected token export(第45行)。

可以通过设置 script 标签的 type 为 module 来修复这个报错:

js 复制代码
<script type="module" src="dist/bundle.js"></script>

系统模块


SystemJs 是一个通用的模块加载器, 支持 CJS,AMD 和 ESM 模块。Rollup 可以将代码打包成 SystemJS 的原生格式。

下面是 Rollup 生成的 System 格式的文件:

js 复制代码
System.register([], (function (exports) {
  'use strict';
  return {
    execute: (function () {

      exports('power', power);

      /**
       * Increase the current total value
       * @param {number} total The current total value
       * @param {number} value The new value to be added
       * @returns {number} The new total value
       */
       const increase = (total, value) => total + value;

      /**
       * Decrease the current total value
       * @param {number} total The current total value
       * @param {number} value The new value to be subtracted
       * @returns {number} The new total value
       */
       const decrease = (total, value) => total - value;

      var others = {
        a: 1,
        b: 2,
        c: () => 3,
      };
      const e = 5;

      /**
       * This is the main file
       */
       
       function multiply(total, value) {
         return total * value;
       }
       
       function power(total, value) {
         return total ** value;
       }
       
       let total = others.a;
       
       total = increase(total, 10);
       total = increase(total, 20);
       total = decrease(total, 5);
       total = multiply(total, e);
       
       console.log(`Total is ${total}`);

    })
  };
}));

我们在浏览器运行这个文件,它会报错,报错信息是 System is not defined(第1行)。 安装 system.js:

js 复制代码
npm install --save-dev systemjs

在 index.html 中引入 system.js 可以解决这个问题:

js 复制代码
<script src="node_modules/systemjs/dist/s.min.js"></script>

立即执行的函数表达式(IIFE)模块


正如模块名所示,IIFE 是一个适合用 <script> 标签引入的自执行函数。我们可以用这种格式为应用创建一个包。它帮助我们将内容放到命名空间中,避免变量冲突并使代码私有。

下面是 Rollup 生成的 IIFE 格式的文件:

js 复制代码
var example = (function (exports) {
  'use strict';

  /**
   * Increase the current total value
   * @param {number} total The current total value
   * @param {number} value The new value to be added
   * @returns {number} The new total value
   */
  const increase = (total, value) => total + value;

  /**
   * Decrease the current total value
   * @param {number} total The current total value
   * @param {number} value The new value to be subtracted
   * @returns {number} The new total value
   */
  const decrease = (total, value) => total - value;

  var others = {
    a: 1,
    b: 2,
    c: () => 3,
  };
  const e = 5;

  /**
   * This is the main file
   */

  function multiply(total, value) {
    return total * value;
  }
  
  function power(total, value) {
    return total ** value;
  }

  let total = others.a;

  total = increase(total, 10);
  total = increase(total, 20);
  total = decrease(total, 5);
  total = multiply(total, e);

  console.log(`Total is ${total}`);

  exports.power = power;

  Object.defineProperty(exports, '__esModule', { value: true });

  return exports;

}({}));

此代码可以在浏览器中运行。

生成多种格式


如果你用 rollup(vite)打包的话,rollup.config.jsRollup 的配置文件。它是可选的,但功能强大,方便,因此推荐使用。

下面是我们来配置一下,一次生成多个输出格式的输出配置:

js 复制代码
output: [
  {
    file: 'dist/bundle.amd.js',
    format: 'amd',
    sourcemap: false,
  },
  {
    file: 'dist/bundle.cjs.js',
    format: 'cjs',
    sourcemap: false,
  },
  {
    file: 'dist/bundle.umd.js',
    format: 'umd',
    name: 'example',
    sourcemap: false,
  },
  {
    file: 'dist/bundle.es.js',
    format: 'es',
    sourcemap: false,
  },
  {
    file: 'dist/bundle.iife.js',
    format: 'iife',
    name: 'example',
    sourcemap: false,
  },
  {
    file: 'dist/bundle.system.js',
    format: 'system',
    sourcemap: false,
  },
]

总结


如果是构建js库,通常我们package.json中的main字段使用umd格式,module字段只用es格式;

#打包类型 #AMD #ES #CJS #UDM #ESM #IIFE #System #构建

相关推荐
前端工作日常18 分钟前
H5 实时摄像头 + 麦克风:完整可运行 Demo 与深度拆解
前端·javascript
韩沛晓29 分钟前
uniapp跨域怎么解决
前端·javascript·uni-app
前端工作日常30 分钟前
以 Vue 项目为例串联eslint整个流程
前端·eslint
程序员鱼皮32 分钟前
太香了!我连夜给项目加上了这套 Java 监控系统
java·前端·程序员
Rubin931 小时前
TS 相关
javascript
该用户已不存在1 小时前
这几款Rust工具,开发体验直线上升
前端·后端·rust
前端雾辰1 小时前
Uniapp APP 端实现 TCP Socket 通信(ZPL 打印实战)
前端
无羡仙1 小时前
虚拟列表:怎么显示大量数据不卡
前端·react.js
云水边1 小时前
前端网络性能优化
前端
用户51681661458411 小时前
[微前端 qiankun] 加载报错:Target container with #child-container not existed while devi
前端