Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 987
Andy Avatar asked Jul 22 '15 23:07

Andy


People also ask

What is external in webpack?

May 4, 2020. Webpack externals tell Webpack to exclude a certain import from the bundle. Often externals are used to exclude imports that will be loaded via CDN. For example, suppose you are implementing server-side rendering with Vue and Express, but your client-side code imports Vue via a CDN.

What does webpack mode production do?

Providing the mode configuration option tells webpack to use its built-in optimizations accordingly.

Does webpack include node_modules?

Webpack builds a dependency graph used internally Now all modules that are used in your app are included in the dependency graph. Your project have many installed dependencies in the node_modules folder that should not be included in your client-side JavaScript production bundle.

How do I use webpack bundle files?

You can bundle your JavaScript using the CLI command by providing an entry file and output path. Webpack will automatically resolve all dependencies from import and require and bundle them into a single output together with your app's script. But that's just the bare minimum it can do.


1 Answers

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/

like image 65
franky Avatar answered Sep 24 '22 10:09

franky