Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add flatMap using babel 7?

After reading the article Removing Babel's Stage Presets by babel, I still not fully understand how to add a proposal from, for example, stage-3 (flatMap) to .babelrc.

As far as I understand, because flatMap can be written in ES5, then I need a polyfill and not a plugin. I installed @babel/polyfill under --save-dev but the browser still tells me that this method doesn't exist. I guess that @babel/polyfill doesn't cover experimental features.

like image 871
Stav Alfi Avatar asked Sep 05 '18 08:09

Stav Alfi


People also ask

Does Babel automatically polyfill?

Babel includes a polyfill that includes a custom regenerator runtime and core-js. This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool. (this polyfill is automatically loaded when using babel-node ).

Do we still need Babel polyfill?

So long story short, just using babel is not enough for your application to work because all the latest Javascript features are not supported in all browsers. So to fix this problem, we need to use a polyfill.

How does Babel polyfill work?

Babel Polyfill adds support to the web browsers for features, which are not available. Babel compiles the code from recent ecma version to the one, which we want. It changes the syntax as per the preset, but cannot do anything for the objects or methods used.


2 Answers

flatMap was removed from @babel/polyfill for babel 7. You need to include it directly from core-js, like

import "core-js/fn/array/flat-map";

Or if you want all of the polyfills that babel 6 used to include:

import "core-js/shim";

See: https://github.com/babel/babel/pull/8440 (or more directly, the relevant section of the v7 upgrade guide)

(Also, don't worry about having to add a new package: you already have core-js in your dependency tree; that's where babel/polyfill gets the rest of its Stage 4+ polyfills)

like image 51
George Avatar answered Oct 01 '22 20:10

George


With core.js 3.x use the following import:

import "core-js/features/array/flat-map";
like image 35
Kirill Avatar answered Oct 01 '22 20:10

Kirill