Using webpack with shims and polyfills

I’ve been getting into webpack a lot lately, partly because of the amazing experience of using React with a hot reloader like react-hot-loader.

If you haven’t used webpack in a project yet, go play around with it right now! For a quick React hot reloader boilerplate checkout react-hot-boilerplate or react-webpack-boilerplate.


In a recent project I wanted to use the new fetch API, if you are not familiar with the background story go read Jack Archibald’s That’s so fetch! post.

The overall browser support is starting to pick up, with Chrome 42(beta), Firefox 39 and Opera 29 all shipping with it by default. Internet Explorer is currently listing it as “under consideration” on their platform status page.

Luckily for us GitHub has been maintaining a great polyfill github/fetch since October 2014, which means we can already use this in production. Using the polyfill without a bundler like webpack would mean adding a <script> tag to your template.

I couldn’t figure out the “webpack way” of including the polyfill in my bundle, and after reading the webpack wiki page on shimming modules I still couldn’t quite figure out the syntax.

That was until I stumbled upon this gist by Luís Couto, showing exactly how to use the fetch polyfill with webpack.

The important part of the webpack config:

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

It uses the imports-loader and exports-loader for webpack, so make sure you have them installed:

$ npm i imports-loader exports-loader -D

For more information about shimming modules in webpack, checkout the documentation.


Update 1: Corrected small typo spotted by @stkhlm, thanks!

Update 2: Updated npm install to use -D for devDependencies, thanks to Gio d’Amelio!