likes
comments
collection
share

利用 webpack 理解 CommonJS 和 ES Modules 的差异

作者站长头像
站长
· 阅读数 13

前言

问: 在 CommonJSES Modules 中,模块导出有什么不同?

  • CommonJS 导出的是值的拷贝;ES Modules 导出的是值的“引用”。

我相信很多人已经把这个答案背得滚瓜烂熟,好,那继续提问。

问:CommonJS 导出的值是浅拷贝还是深拷贝?

问:你能模拟实现 ES Modules 的导出机制吗?

对于以上两个问题,我也是感到一脸懵逼,好在有 webpack 的帮助,作为一个打包工具,它让 ES ModulesCommonJS 的工作流程瞬间清晰明了。

准备工作

初始化项目,并安装 beta 版本的 webpack 5,它相较于 webpack 4 做了许多优化:对 ES Modules 的支持度更高,打包后的代码也更精简。

$ mkdir demo && cd demo
$ yarn init -y
$ yarn add webpack@next webpack-cli
# or yarn add webpack@5.0.0-beta.17 webpack-cli

早在 webpack4 就已经引入了无配置的概念,既不需要提供 webpack.config.js 文件,它会默认以 src/index.js 为入口文件,生成打包后的 main.js 放置于 dist 文件夹中。

确保你拥有以下目录结构:

├── dist
│   └── index.html
├── src
│   └── index.js
├── package.json
└── yarn.lock

index.html 中引入打包后的 main.js

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>

package.json 中添加命令脚本:

"scripts": {
  "start": "webpack"
},

运行无配置打包:

$ yarn start

终端会提示:

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

webpack 要求用户在打包时必须提供 mode 选项,来指明打包后的资源用于开发环境还是生产环境,从而让 webpack 相应地使用其内置优化,默认为 production(生产环境)。

我们将其设置为 none 来避免默认行为带来的干扰,以便我们更好的分析源码。

修改 package.json

"scripts": {
  "start": "webpack --mode=none"
},

重新运行,webpack 在 dist 目录下生成了打包后的 main.js,由于入口文件是空的,所以 main.js 的源码只有一个 IIFE(立即执行函数),看似简单,但它的地位却极其重要。

(() => {
  // webpackBootstrap
})();

我们知道无论在 CommonJS 或 ES Modules 中,一个文件就是一个模块,模块之间的作用域相互隔离,且不会污染全局作用域。此刻 IIFE 就派上了用场,它将一个文件的全部 JS 代码包裹起来,形成闭包函数,不仅起到了函数自执行的作用,还能保证函数间的作用域不会互相污染,并且在闭包函数外无法直接访问内部变量,除非内部变量被显式导出。

var name = "webpack";

(() => {
  var name = "parcel";
  var age = 18;
  console.log(name); // parcel
})();

console.log(name); // webpack
console.log(age); // ReferenceError: age is not defined

拷贝 vs 引用

接下里进入实践部分,涉及源码的阅读,让我们深入了解 CommonJSES Modules 的差异所在。

CommonJS

新建 src/counter.js

let num = 1;

function increase() {
  return num++;
}

module.exports = { num, increase };

修改 index.js

const { num, increase } = require("./counter");

console.log(num);
increase();
console.log(num);

如果你看过前面叙述,毫无疑问,打印 1 1.

so why?我们查看 main.js,那有我们想要的答案,去除无用的注释后如下:

(() => {
  var __webpack_modules__ = [
    ,
    module => {
      let num = 1;

      function increase() {
        return num++;
      }

      module.exports = { num, increase };
    },
  ];

  var __webpack_module_cache__ = {};

  function __webpack_require__(moduleId) {
    // Check if module is in cache
    if (__webpack_module_cache__[moduleId]) {
      return __webpack_module_cache__[moduleId].exports;
    }
    // Create a new module (and put it into the cache)
    var module = (__webpack_module_cache__[moduleId] = {
      exports: {},
    });

    // Execute the module function
    __webpack_modules__[moduleId](module, module.exports, __webpack_require__);

    return module.exports;
  }

  (() => {
    const { num, increase } = __webpack_require__(1);

    console.log(num);
    increase();
    console.log(num);
  })();
})();

可以简化为:

(() => {
  var __webpack_modules__ = [...];
  var __webpack_module_cache__ = {};

  function __webpack_require__(moduleId) {...}

  (() => {
    const { num, increase } = __webpack_require__(1);

    console.log(num);
    increase();
    console.log(num);
  })();
})();

最外层是一个 IIFE,立即执行。

__webpack_modules__,它是一个数组,第一项为空,第二项是一个箭头函数并传入 module 参数,函数内部包含了 counter.js 中的所有代码。

__webpack_module_cache__ 缓存已经加载过的模块。

function __webpack_require__(moduleId) {...} 类似于 require(),他会先去 __webpack_module_cache__ 中查找此模块是否已经被加载过,如果被加载过,直接返回缓存中的内容。否则,新建一个 module: {exports: {}},并设置缓存,执行模块函数,最后返回 module.exports

最后遇到一个 IIFE,它将 index.js 中的代码包装在内,并执行 __webpack_require__(1),导出了 numincreaseindex.js 使用。

这里的关键点在于 counter.js 中的 module.exports = { num, increase };,等同于以下写法:

module.exports = {
  num: num,
  increase: increase,
};

num 属于基本类型,假设其内存地址指向 n1,当它被 赋值module.exports['num'] 时,module.exports['num'] 已经指向了一个新的内存地址 n2,只不过其值同样为 1,但和 num 已是形同陌路,毫不相干。

let num = 1;
// mun 相当于 module.exports['num']
mun = num;

num = 999;
console.log(mun); // 1

increase 是一个函数,属于引用类型,即 increase 只作为一个指针,当它被赋值给 module.exports['increase'] 时,只进行了指针的复制,是 浅拷贝(基本类型没有深浅拷贝的说法),其内存地址依旧指向同一块数据。所以本质上 module.exports['increase'] 就是 increase,只不过换个名字。

而由于词法作用域的特性,counter.jsincrease() 修改的 num 变量在函数声明时就已经绑定不变了,永远绑定内存地址指向 n1num.

JavaScript 采用的是词法作用域,它规定了函数内访问变量时,查找变量是从函数声明的位置向外层作用域中查找,而不是从调用函数的位置开始向上查找

var x = 10;

function foo() {
  console.log(x);
}

function bar(f) {
  var x = 20;
  f();
}

bar(foo); // 10 instead of 20

调用 increase() 并不会影响内存地址指向 n2num,这也就是为什么打印 1 1 的理由。

ES Modules

分别修改 counter.jsindex.js,这回使用 ES Modules.

let num = 1;

function increase() {
  return num++;
}

export { num, increase };
import { num, increase } from "./counter";

console.log(num);
increase();
console.log(num);

很明显,打印 1 2.

老规矩,查看 main.js,删除无用的注释后如下:

(() => {
  "use strict";
  var __webpack_modules__ = [
    ,
    (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
      __webpack_require__.d(__webpack_exports__, {
        num: () => /* binding */ num,
        increase: () => /* binding */ increase,
      });
      let num = 1;

      function increase() {
        return num++;
      }
    },
  ];

  var __webpack_module_cache__ = {};

  function __webpack_require__(moduleId) {} // 笔者注:同一个函数,不再展开

  /* webpack/runtime/define property getters */
  (() => {
    __webpack_require__.d = (exports, definition) => {
      for (var key in definition) {
        if (
          __webpack_require__.o(definition, key) &&
          !__webpack_require__.o(exports, key)
        ) {
          Object.defineProperty(exports, key, {
            enumerable: true,
            get: definition[key],
          });
        }
      }
    };
  })();

  /* webpack/runtime/hasOwnProperty shorthand */
  (() => {
    __webpack_require__.o = (obj, prop) =>
      Object.prototype.hasOwnProperty.call(obj, prop);
  })();

  (() => {
    var _counter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);

    console.log(_counter__WEBPACK_IMPORTED_MODULE_0__.num);
    (0, _counter__WEBPACK_IMPORTED_MODULE_0__.increase)();
    console.log(_counter__WEBPACK_IMPORTED_MODULE_0__.num);
  })();
})();

经过简化,大致如下:

(() => {
  "use strict";
  var __webpack_modules__ = [...];
  var __webpack_module_cache__ = {};

  function __webpack_require__(moduleId) {...}

  (() => {
    __webpack_require__.d = (exports, definition) => {...};
  })();

  (() => {
    __webpack_require__.o = (obj, prop) => {...}
  })();

  (() => {
    var _counter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);

    console.log(_counter__WEBPACK_IMPORTED_MODULE_0__.num);
    (0, _counter__WEBPACK_IMPORTED_MODULE_0__.increase)();
    console.log(_counter__WEBPACK_IMPORTED_MODULE_0__.num);
  })();
})();

首先查看两个工具函数:__webpack_require__.o__webpack_require__.d

__webpack_require__.o 封装了 Object.prototype.hasOwnProperty.call(obj, prop) 的操作。

__webpack_require__.d 则是通过 Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }) 来对 exports 对象设置不同属性的 getter

随后看到了熟悉的 __webpack_modules__,它的形式和上一节差不多,最主要的是以下这段代码:

__webpack_require__.d(__webpack_exports__, {
  num: () => /* binding */ num,
  increase: () => /* binding */ increase,
});

CommonJS 不同,ES Modules 并没有对 module.exports 直接赋值,而是将值作为箭头函数的返回值,再把箭头函数赋值给 module.exports,之前我们提过词法作用域的概念,即这里的 num()increase() 无论在哪里执行,返回的 num 变量和 increase 函数都是 counter.js 中的。

在遇到最后一个 IIFE 时,调用 __webpack_require__(1),返回 module.exports 并赋值给 _counter__WEBPACK_IMPORTED_MODULE_0__,后续所有的属性获取都是使用点操作符,这触发了对应属性的 get 操作,于是执行函数返回 counter.js 中的值。

所以打印 1 2.

这里有一个额外知识点,就是当你尝试在 index.js 中直接对 import 的 num 变量或者 increase 函数重新赋值时,浏览器会抛出错误:

Uncaught TypeError: Cannot set property num of #<Object> which has only a getter

还记得 webpack 之前对 exports 对象做了一个设置 getter 的操作吗?其实质是设置了 exports 对象的 存取描述符,而 setter 并未设置,默认为 undefined

且在严格模式下("use strict"),如果对 exports 对象进行属性赋值操作,会导致错误。

webpack 这么设计的原因是要与 ES Modules 的规范保持一致,即模块导出的值是 只读的,你无法在 index.js 中直接修改它,只能借助 counter.js 导出的方法 increase() 去间接修改。

在浏览器原生实现的 ES Modules 中,即使使用 varlet 去声明,也会报错:无法对常量进行重新赋值。

Uncaught TypeError: Assignment to constant variable.

说了这么多,懂了词法作用域的原理,你就可以实现一个“乞丐版”的 ES Modules

function my_require() {
  var module = {
    exports: {},
  };
  let counter = 1;

  function add() {
    return counter++;
  }

  module.exports = { counter: () => counter, add };
  return module.exports;
}

var obj = my_require();

console.log(obj.counter()); // 1
obj.add();
console.log(obj.counter()); // 2

总结

多去看源码,会有不少的收获,这是一个思考的过程。

早年,浏览器既不支持 ES Modules,也不支持 CommonJS.

ES Modules 早在 ES2015 就被写入了规范中,但彼时还是 CommonJS 的天下。

如今,随着浏览器厂商的原生支持以及 ES2020 引入了 Dynamic Import,其前景可谓一片光明,有兴趣的小伙伴可以试试 Snowpack,它能直接 export 第三方库供浏览器运行,省去了 webpack 中打包的时间。