使用 babel 和 webpack 减少转译代码助手

Reduce transpiled code helpers with babel and webpack

在我的项目中,我使用 babel to transpile down to ES5. I'm using webpack to bundle everything together. There are several places where babel adds a function at the top of any given file to support some feature (like rest params here or import statements here).

例如,几乎每个文件的顶部都有这个:

var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

几个文件有这个:

var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } };

在我的 smaller project 中,这不是什么大问题,但在我工作的项目中,我正在做同样的事情,我确信我可以通过计算出更多的字节数一种将所有这些 polyfill 放在一个地方并让 babel/webpack 引用它们的方法。因此,与其在每个使用 import 的文件(几乎每个文件)中都包含 _interopRequire,不如将其放在一个位置并被引用。

有办法吗?

前段时间我也有同样的问题,文档里有明确的答案:

https://babeljs.io/docs/en/babel-runtime

在 webpack 配置中你可以像 'babel?optional=runtime'

那样做

我不确定如何处理图书馆或小项目。我认为您不会真正从使用外部助手中获得任何好处。但是,对于我的应用程序,我发现在 gzip 压缩之后,它实际上比包含帮助程序时更小。

Babel has a few helper functions that'll be placed at the top of the generated code if needed so it's not inlined multiple times throughout that file. This may become an issue if you have multiple files, especially when you're sending them to the browser. gzip alleviates most of this concern but it's still not ideal.

(强调)

这就是我的解决方案,我对此很满意。 (基本上不用担心)。

使用Babel Runtime,

Since these helpers can get pretty long, and they get added to the top of every file you can move them into a single "runtime" which gets required.

Start by installing babel-plugin-transform-runtime and babel-runtime:

$ npm install --save-dev babel-plugin-transform-runtime
$ npm install --save babel-runtime