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

WebpackCdnProductionWebpack Externals

Webpack Problem Overview


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.

Webpack Solutions


Solution 1 - Webpack

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/

Solution 2 - Webpack

I created https://github.com/mastilver/dynamic-cdn-webpack-plugin which is doing exactly that out of the box

const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const DynamicCDNWebpackPlugin = require('dynamic-cdn-webpack-plugin')

module.exports = {
  entry: './main.js',
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  plugins: [
    new HTMLWebpackPlugin(),
    new DynamicCDNWebpackPlugin()
  ]
}

Will dynamically add unpkg.org urls and add the appropriate code in your bundle to load librairies from global

Solution 3 - Webpack

All the development-only portions of the React codebase, such as PropType checks, are guarded with:

if ("production" !== process.env.NODE_ENV) {
  ..
}

To strip these out from React in your own build, creating the equivalent of the minified React build in your own bundle, use DefinePlugin to replace references to process.env.NODE_ENV with "production".

plugins: [
  // ...
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify('production')
  }),
  new webpack.optimize.UglifyJsPlugin({
    compressor: {
      warnings: false
    }
  })
  // ...
],

Uglify's dead code elimination will then strip it all out, as it will detect that code wrapped with a "production" !== "production" check is unreachable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndyView Question on Stackoverflow
Solution 1 - WebpackfrankyView Answer on Stackoverflow
Solution 2 - WebpackmastilverView Answer on Stackoverflow
Solution 3 - WebpackJonny BuchananView Answer on Stackoverflow