Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce transpiled code helpers with babel and webpack

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?

like image 296
kentcdodds Avatar asked Jun 12 '15 11:06

kentcdodds


People also ask

How do you speed up Babel?

You can also speed up babel-loader by as much as 2x by using the cacheDirectory option. This will cache transformations to the filesystem.

What is the difference between Babel and Webpack?

Babel can be classified as a tool in the "JavaScript Compilers" category, while Webpack is grouped under "JS Build Tools / JS Task Runners".

Is babel-loader deprecated?

Since @babel/polyfill was deprecated in 7.4.0, we recommend directly adding core-js and setting the version via the corejs option.


1 Answers

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'

like image 79
Bogdan Savluk Avatar answered Oct 04 '22 08:10

Bogdan Savluk