8

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.

Stav Alfi
  • 13,139
  • 23
  • 99
  • 171

2 Answers2

14

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)

George
  • 4,147
  • 24
  • 33
  • Is there a way to use a proposal without explicitly import it in the code? – Stav Alfi Sep 07 '18 at 06:05
  • `node -r core-js/fn/array/flat-map ...` for server code, or include it as a webpack entrypoint for browser code. – George Sep 07 '18 at 17:45
  • could you please show an example of the configuration inside webpack 4? one minute of your time worth a lot for me. – Stav Alfi Sep 07 '18 at 18:32
  • also, is this solution will add `flatMap` to an array or as an independent function? – Stav Alfi Sep 07 '18 at 18:33
  • Add it as en entry-point, per: https://webpack.js.org/concepts/entry-points/ And it both writes to `Array.prototype.flatMap` (if not already available) and exports the function (`import flatMap from "core-js/..."`). – George Sep 08 '18 at 23:12
4

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

import "core-js/features/array/flat-map";
Kirill
  • 6,762
  • 4
  • 51
  • 81