Reduce transpiled code helpers with babel and webpack

1.8k views Asked by At

In my project, I'm using 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).

For example, pretty much every file has this at the top:

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

And several files have this:

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); } };

In my smaller project this isn't a huge deal, but in my project at work, I'm doing the same thing and I'm sure I could shave more than a few bytes by figuring out a way to just have all of these polyfills in one place and have babel/webpack reference those. So rather than having _interopRequire in every file that's using import (which is almost every file), have it in one place and be referenced.

Is there a way to do this?

3

There are 3 answers

0
kentcdodds On BEST ANSWER

I'm not sure what to do about a library or small project. I'm thinking you wouldn't really get any benefit from using the external helpers. However, for my application, I found that after gzipping, it's actually smaller than if I include the helpers.

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.

(emphasis added)

So that's my solution and I'm happy with that. (Basically, don't worry about it).

4
Bogdan Savluk On

I had the same question some time ago, and there is clear answer in documentation:

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

In webpack config you can do it just as 'babel?optional=runtime'

0
Savitoj Cheema On

Use 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