Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel not Polyfilling Fetch when using babel-preset-env

I'm using Webpack and Babel to build and transpile my ES6 code. However I am missing important Polyfills when trying to support older browsers. e.g iOS8.

Here's my Webpack.config

const versions = {
  v1: './src/js/v1.js',
  v2: './src/js/v2.js',
  v3: './src/js/v3.js',
};

module.exports = {
  entry: versions,
  output: {
    path: __dirname + '/dist',
    filename: '[name].min.js'
  },
  externals: {
    'jquery': 'jQuery'
  },
  module: {
    loaders: [
      { 
        test: /\.js$/, 
        exclude: /node_modules/, 
        loader: 'babel-loader',
      }, {
        test: /\.hbs$/,
        loader: 'handlebars-loader',
      }
    ]
  }
}

And my .babelrc file:

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 3 versions", "iOS >= 8"]
      }
    }]
  ]
}

Firstly, why isn't this Polyfill being added? And secondly how do I add it? I attempted adding this to my .babelrc "plugins": ["whatwg-fetch"] with no luck.

I believe I can add it to the entry of my Webpack config, but that won't work in my instance as I have multiple scripts I am trying to build separately.

Thanks in advance for any help. My diminishing head of hair is especially thankful!

like image 212
DanV Avatar asked Jul 04 '17 14:07

DanV


People also ask

What is preset ENV in Babel?

@babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!

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.


1 Answers

You can add the resolution of fetch inside your webpack.config.js file.

new webpack.ProvidePlugin({
  'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
})

Inside your plugins section. After that, inside your code, just use fetch. You won't need to import it whatsoever. Of course, you need imports-loader and exports-loader.

like image 122
Ematipico Avatar answered Sep 24 '22 12:09

Ematipico