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

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/


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