Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

webpack - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...