45

I'm trying to exclude react from my bundle which is generated by webpack. Reason being, we have a global version of react available on the page so I'll be using that.

I have tried using the below, as suggested here Webpack and external libraries but this doesn't seem to work. I can see webpack has exported React but it still appears in the bundle.

externals: {
  'react': 'React'
}

I was thinking it may be another dependency e.g. react-router importing react? Has anyone managed to do this?

Community
  • 1
  • 1
r.gregory
  • 451
  • 1
  • 4
  • 3

3 Answers3

43

I had the same problem as you did. Was stuck for one night, found the answer, react-dom requires react/lib/ReactDOM, which still includes react in the bundle. Solution looks like this:

externals: {
 'react': 'react', // Case matters here 
 'react-dom' : 'reactDOM' // Case matters here 
}

Then add react-dom to the script tag in your page.

Joshua Robinson
  • 3,430
  • 1
  • 27
  • 35
xuehan
  • 571
  • 4
  • 4
19

webpack config:

externals: {
    'react': 'React',
    'react-dom': 'ReactDOM',
    'react-router': 'ReactRouter'
}

add these to the bottom of index.html body.

<script src="http://cdn.bootcss.com/react/15.4.1/react.js"></script>
<script src="http://cdn.bootcss.com/react/15.4.1/react-dom.js"></script>
<script src="http://cdn.bootcss.com/react-router/2.8.1/ReactRouter.js"></script>

and, in your entry file, maybe index.js:

var React = require('react');
var ReactDOM = require('react-dom');
var ReactRouter = require('react-router');

const App = () => {
    return <div>
        webpack externals
    </div>
};

ReactDOM.render(
    <App/>,
    document.getElementById('container')
);
Facundo La Rocca
  • 3,786
  • 2
  • 25
  • 47
Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • And, you can inject `script` tag using some webpack plugin like `htmlwebpackplugin` or write a node/shell script to do this by yourself. But this is another question – Lin Du Jul 28 '18 at 00:59
-3

You can just create multiple entries to separate react from your application bundle. You can for example do the following, using the webpack CommonsChunkPlugin :

module.exports = {
entry: {
    "app": "your app entry file",
    "react" : "react"
},
plugins: [
    new webpack.optimize.CommonsChunkPlugin("react", "react.bundle.js")
   ]
}
Facundo La Rocca
  • 3,786
  • 2
  • 25
  • 47