How to use a library from a CDN in a Webpack project in production

Andy picture Andy · Jul 23, 2015 · Viewed 28.6k times · Source

I'd like to use react.min.js from a CDN in production (e.g. https://unpkg.com/[email protected]/dist/react.min.js)

What is the best way to get Webpack to transform my import React from 'react' statements into const React = window.React instead of building node_modules/react into the bundle?

I've been doing it with resolve.alias like this:

In index.html:

<head>
  <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/react.min.js"></script>
  <script type="text/javascript" src="/assets/bundle.js"></script>
</head>

In webpack.prod.config.js:

alias: {
  react$: './getWindowReact',
},

getWindowReact.js:

module.exports = window.React;

Note: In the old question I didn't realize that building React into a Webpack bundle with NODE_ENV=production would strip out the propTypes checks. One of the answers focuses on that.

Answer

franky picture franky · Jul 23, 2015

In your webpack config you can use the externals option which will import the module from the environment instead of trying to resolve it normally:

// webpack.config.js
module.exports = {
  externals: {
    'react': 'React'
  }
  ...
};

Read more here: https://webpack.js.org/configuration/externals/