本文你将学到:
- Rollup 是什么
- CommonJS、AMD、CMD、UMD、ES6 分别的介绍
- ES6 模块与 CommonJS 模块的区别
- 模块演进的产物 —— Tree Shaking
- Tree Shaking 应该注意什么
本文所有例子都存放于 https://github.com/hua1995116/packaging-example
引言
今天在使用 rollup 打包的时候遇到了一个问题
1Error: 'Map' is not exported by node_modules/immutable/dist/immutable.js 2typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 3 typeof define === 'function' && define.amd ? define(factory) : 4 global.Immutable = factory();
发现 immutable 是以 UMD 的形式暴露。查阅资料后发现 Rollup 并不支持 CommonJS 和 AMD 的打包方式,想要成功引入 commonJS 的模块,必须要加载插件 https://github.com/rollup/plugins/tree/master/packages/commonjs。 当然并不是对所有的 CommonJS 都自动支持,只针对类似于静态的写法才能导出,例如针动态模块导出,以及隐式地导出将无法自动导出,这样的场景下需要手动指定导出模块。以上的例子就是一个动态的方式,只有当 factory 函数执行了才能知道导出的模块,需要手动指定。
1commonjs({ 2 namedExports: { 3 // left-hand side can be an absolute path, a path 4 // relative to the current directory, or the name 5 // of a module in node_modules 6 'immutable': ['Map'] 7 } 8});
当然上述只是我写这篇文章的一个起因,就是因为我对这一块的迷惑,所以使得我想重新复习一下这一块知识,上面将的可能你完全听不懂我在说什么,没有关系,下面开始切入正题。
Rollup 是什么?
因为在最一开始,是我引入了这个概念,所以由我出来填坑,当然对这个工具非常熟悉的朋友可以跳过。不熟悉的朋友你只需要知道,这个是一个打包 ES Module 的工具。
Rollup 是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,例如 library 或应用程序。Rollup 对代码模块使用新的标准化格式,这些标准都包含在 JavaScript 的 ES6 版本中,而不是以前的特殊解决方案,如 CommonJS 和 AMD。ES6 模块可以使你自由、无缝地使用你最喜爱的 library 中那些最有用独立函数,而你的项目不必携带其他未使用的代码。ES6 模块最终还是要由浏览器原生实现,但当前 Rollup 可以使你提前体验。
CommonJS
CommonJS 主要运行于服务器端,该规范指出,一个单独的文件就是一个模块。 Node.js为主要实践者,它有四个重要的环境变量为模块化的实现提供支持:module、exports、require、global。require 命令用于输入其他模块提供的功能,module.exports命令用于规范模块的对外接口,输出的是一个值的拷贝,输出之后就不能改变了,会缓存起来。
1// 模块 a.js 2const name = 'qiufeng' 3 4module.exports = { 5 name, 6 github: 'https://github.com/hua1995116' 7} 8// 模块 b.js 9// 引用核心模块或者第三方包模块,不需要写完整路径 10const path = require('path'); 11// 引用自定义模块可以省略.js 12const { name, github } = require('./a'); 13 14console.log(name, github, path.basename(github)); 15// 输出 qiufeng https://github.com/hua1995116 hua1995116
代码地址: https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/CommonJS
CommonJS 采用同步加载模块,而加载的文件资源大多数在本地服务器,所以执行速度或时间没问题。但是在浏览器端,限于网络原因,更合理的方案是使用异步加载。
AMD
AMD是"Asynchronous Module Definition"的缩写,意思就是"异步模块定义"。它采用异步方式加载模块,模块的加载不影响它后面语句的运行。所有依赖这个模块的语句,都定义在一个回调函数中,等到加载完成之后,这个回调函数才会运行。其中 RequireJS 是最佳实践者。
模块功能主要的几个命令:define、require、return和define.amd。define是全局函数,用来定义模块,define(id?, dependencies?, factory)。require命令用于输入其他模块提供的功能,return命令用于规范模块的对外接口,define.amd属性是一个对象,此属性的存在来表明函数遵循AMD规范。
1// model1.js 2define(function () { 3 console.log('model1 entry'); 4 return { 5 getHello: function () { 6 return 'model1'; 7 } 8 }; 9}); 10// model2.js 11define(function () { 12 console.log('model2 entry'); 13 return { 14 getHello: function () { 15 return 'model2'; 16 } 17 }; 18}); 19// main.js 20define(function (require) { 21 var model1 = require('./model1'); 22 console.log(model1.getHello()); 23 var model2 = require('./model2'); 24 console.log(model2.getHello()); 25}); 26<script src="https://cdn.bootcss.com/require.js/2.3.6/require.min.js"></script> 27<script> 28 requirejs(['main']); 29</script> 30// 输出结果 31// model1 entry 32// model2 entry 33// model1 34// model2
代码地址: https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/AMD
在这里,我们使用define来定义模块,return来输出接口, require来加载模块,这是AMD官方推荐用法。
CMD
CMD(Common Module Definition - 通用模块定义)规范主要是Sea.js推广中形成的,一个文件就是一个模块,可以像Node.js一般书写模块代码。主要在浏览器中运行,当然也可以在Node.js中运行。
它与AMD很类似,不同点在于:AMD 推崇依赖前置、提前执行,CMD推崇依赖就近、延迟执行。
不懂 依赖就近、延迟执行 的可以比较下面和上面的例子。
1// model1.js 2define(function (require, exports, module) { 3 console.log('model1 entry'); 4 exports.getHello = function () { 5 return 'model1'; 6 } 7}); 8// model2.js 9define(function (require, exports, module) { 10 console.log('model2 entry'); 11 exports.getHello = function () { 12 return 'model2'; 13 } 14}); 15// main.js 16define(function(require, exports, module) { 17 var model1 = require('./model1'); //在需要时申明 18 console.log(model1.getHello()); 19 var model2 = require('./model2'); //在需要时申明 20 console.log(model2.getHello()); 21}); 22<script src="https://cdn.bootcss.com/seajs/3.0.3/sea.js"></script> 23<script> 24 seajs.use('./main.js') 25</script> 26// 输出 27// model1 entry 28// model1 29// model2 entry 30// model2
https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/CMD
总结: 对比和 AMD 的写法就可以看出 AMD 和 CMD 的区别。虽然现在 CMD 已经凉了。但是 CMD 更加接近于 CommonJS 的写法,但是 AMD 更加接近于浏览器的异步的执行方式。
UMD
UMD(Universal Module Definition - 通用模块定义)模式,该模式主要用来解决CommonJS模式和AMD模式代码不能通用的问题,并同时还支持老式的全局变量规范。
示例展示
1// bundle.js 2(function (global, factory) { 3 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 4 typeof define === 'function' && define.amd ? define(factory) : 5 (global = global || self, global.myBundle = factory()); 6}(this, (function () { 'use strict'; 7 8 var main = () => { 9 return 'hello world'; 10 }; 11 12 return main; 13 14}))); 15// index.html 16<script src="bundle.js"></script> 17<script> 18 console.log(myBundle()); 19</script>
- 判断
define为函数,并且是否存在define.amd,来判断是否为AMD规范, - 判断
module是否为一个对象,并且是否存在module.exports来判断是否为CommonJS规范 - 如果以上两种都没有,设定为原始的代码规范。
代码地址:https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/UMD
ES Modules
ES modules(ESM)是 JavaScript 官方的标准化模块系统。
- 它因为是标准,所以未来很多浏览器会支持,可以很方便的在浏览器中使用。(浏览器默认加载不能省略.js)
- 它同时兼容在node环境下运行。
- 模块的导入导出,通过
import和export来确定。 可以和Commonjs模块混合使用。 - ES modules 输出的是值的引用,输出接口动态绑定,而 CommonJS 输出的是值的拷贝
- ES modules 模块编译时执行,而 CommonJS 模块总是在运行时加载
使用方式
1// index.js 2import { name, github } from './demo.js'; 3 4console.log(name(), github()); 5 6document.body.innerHTML = `<h1>${name()} ${github()}</h1>` 7export function name() { 8 return 'qiufeng'; 9} 10 11export function github() { 12 return 'https://github.com/hua1995116'; 13} 14<script src="./index.js" type="module"></script>
代码地址: https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/ES-Modules
详细可以查看 深入理解 ES6 模块机制
CommonJS 的值拷贝
1// a.js 2const b = require('./b'); 3console.log(b.age); 4setTimeout(() => { 5 console.log(b.age); 6 console.log(require('./b').age); 7}, 100); 8// b.js 9let age = 1; 10setTimeout(() => { 11 age = 18; 12}, 10); 13module.exports = { 14 age 15} 16// 执行:node a.js 17// 执行结果: 18// 1 19// 1 20// 1
CommonJS 主要有执行主要有以下两个特点
- CommonJS 模块中 require 引入模块的位置不同会对输出结果产生影响,并且会生成值的拷贝
- CommonJS 模块重复引入的模块并不会重复执行,再次获取模块只会获得之前获取到的模块的缓存
ES modules 的值的引用
1// a.js 2import { age } from './b.js'; 3 4console.log(age); 5setTimeout(() => { 6 console.log(age); 7 import('./b.js').then(({ age }) => { 8 console.log(age); 9 }) 10}, 100); 11 12// b.js 13export let age = 1; 14 15setTimeout(() => { 16 age = 2; 17}, 10); 18// 打开 index.html 19// 执行结果: 20// 1 21// 2 22// 2
动态加载和静态编译区别?
举个例子如下:
动态加载,只有当模块运行后,才能知道导出的模块是什么。
1var test = 'hello' 2module.exports = { 3 [test + '1']: 'world' 4}
静态编译, 在编译阶段就能知道导出什么模块。
export function hello() {return 'world'}
关于 ES6 模块编译时执行会导致有以下两个特点:
- import 命令会被 JavaScript 引擎静态分析,优先于模块内的其他内容执行。
- export 命令会有变量声明提前的效果。
import 优先执行:
1// a.js 2console.log('a.js') 3import { age } from './b.js'; 4 5// b.js 6export let age = 1; 7console.log('b.js 先执行'); 8 9// 运行 index.html 执行结果: 10// b.js 先执行 11// a.js
虽然 import 顺序比较靠后,但是 由于 import 提升效果会优先执行。
export 变量声明提升:
1// a.js 2import { foo } from './b.js'; 3console.log('a.js'); 4export const bar = 1; 5export const bar2 = () => { 6 console.log('bar2'); 7} 8export function bar3() { 9 console.log('bar3'); 10} 11 12// b.js 13export let foo = 1; 14import * as a from './a.js'; 15console.log(a); 16 17// 运行 node --experimental-modules a.js 执行结果: 18// [Module] { 19// bar: <uninitialized>, 20// bar2: <uninitialized>, 21// bar3: [Function: bar3] 22}
从上述例子中可以看出,a 模块引用了 b 模块,b 模块也引用了 a 模块,export 声明优先于其他内容。由于变量和函数的提升不一样,此处不做过多介绍。
此处有一个小插曲,我一开始用浏览器进行执行的结果为:
1{ 2 bar: 1 3 bar2: () => { console.log('bar2'); } 4 bar3: ƒ bar3() 5} 6a.js
让我一度觉得是不是 export 有什么特殊的声明提升?因为我发现深入理解 ES6 模块机制一文中是使用的 babel-node, 是否是因为环境不一样导致的。因此我使用了 node v12.16.0,进行测试 node --experimental-modules a.js, 发现结果与 深入理解 ES6 模块机制 中结果一致,后来想到 console.log 的显示问题,console.log 常常会有一些异步的显示。后来我经过测试发现确实是 console.log 搞的鬼
console.log(a); -> console.log(JSON.stringify(a))
会出现一个 Uncaught ReferenceError: bar is not defined 的错误,是因为 bar 未初始化导致。后续也会将这个 console 的表现形式报告给 chromium。
Tree shaking
介绍完了,各个模块的标准后,为什么又将这个 Tree shaking 呢?因为模块化的一次又一次地变更,让我们的模块系统变得越来越好,而 Tree shaking 就是得益 ES modules 的发展的产物。
这个概念是Rollup提出来的。Rollup推荐使用ES2015 Modules来编写模块代码,这样就可以使用Tree-shaking来对代码做静态分析消除无用的代码,可以查看Rollup网站上的REPL示例,代码打包前后之前的差异,就会清晰的明白Tree-shaking的作用。
- 没有使用额外的模块系统,直接定位import来替换export的模块
- 去掉了未被使用的代码
tree shaking 的实际例子
1// main.js 2import * as utils from './utils'; 3 4const array = [1,2,3,1,2,3] 5 6console.log(utils.arrayUnique(array));
代码地址:https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/Tree-Shaking
Tree shaking 和 没有Tree shaking 打包对比。

没有 Tree-shaking 的情况下,会将 utils 中的所有文件都进行打包,使得体积暴增。
ES Modules 之所以能 Tree-shaking 主要为以下四个原因(摘自尤雨溪在知乎的回答):
import只能作为模块顶层的语句出现,不能出现在 function 里面或是 if 里面。import的模块名只能是字符串常量。- 不管
import的语句出现的位置在哪里,在模块初始化的时候所有的import都必须已经导入完成。 import binding是immutable的,类似 const。比如说你不能 import { a } from ‘./a’ 然后给 a 赋值个其他什么东西。
tree shaking 应该注意什么
副作用
没错,就是副作用,那么什么是副作用呢,请看下面的例子。
1// effect.js 2console.log(unused()); 3export function unused() { 4 console.log(1); 5} 6// index.js 7import {unused} from './effect'; 8console.log(42);
此例子中 console.log(unused()); 就是副作用。在 index.js 中并不需要这一句 console.log。而 rollup 并不知道这个全局的函数去除是否安全。因此在打包地时候你可以显示地指定treeshake.moduleSideEffects 为 false,可以显示地告诉 rollup 外部依赖项没有其他副作用。
不指定的情况下的打包输出。 npx rollup index.js --file bundle.js
1console.log(unused()); 2 3function unused() { 4 console.log(1); 5} 6 7console.log(42);
指定没有副作用下的打包输出。npx rollup index.js --file bundle-no-effect.js --no-treeshake.moduleSideEffects
console.log(42);
代码地址: https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/Tree-Shaking-Effect
当然以上只是副作用的一种,详情其他几种看查看 https://rollupjs.org/guide/en/
结语
CommonJS 同步加载, AMD 异步加载, UMD = CommonJS + AMD , ES Module 是标准规范, 取代 UMD,是大势所趋。 Tree-shaking 牢记副作用。
参考
https://github.com/rollup/rollup/issues/3011#issuecomment-516084596
https://github.com/rollup/plugins/tree/master/packages/commonjs
https://www.zhihu.com/question/63240671
https://www.yuque.com/baichuan/notes/emputh
https://github.com/indutny/webpack-common-shake#limitations
http://xbhong.top/2018/03/12/commonjs/
https://www.douban.com/note/283566440/
https://blog.fundebug.com/2018/08/15/reduce-js-payload-with-tree-shaking/