mikejw
mikejw

Reputation: 183

ReactDom is not defined with react and webpack

I've followed this straightforward tutorial (http://jslog.com/2014/10/02/react-with-webpack-part-1/) for getting started with React and webpack but run into issues when trying to use more updated syntax. i.e. using ReactDom to call render instead of the deprecated 'React.renderComponent'.

I've run:

npm install --save react-dom

and added

var ReactDom = require('react-dom')

to the index.jsx file and added

'react-dom': 'ReactDom'

to the list of 'externals' in webpack.config.js. (I'm not sure if this was necessary.)

However I am getting the javascript error ReactDom is not defined.

webpack.config.js:

module.exports = {
entry: './index.jsx',
output: {
    filename: 'bundle.js', //this is the default name, so you can skip it
    //at this directory our bundle file will be available
    //make sure port 8090 is used when launching webpack-dev-server
    publicPath: 'http://localhost:8090/assets'
},
module: {
    loaders: [
        {
            //tell webpack to use jsx-loader for all *.jsx files
            test: /\.jsx$/,
            loader: 'jsx-loader?insertPragma=React.DOM&harmony'
        }
    ]
},
externals: {
    //don't bundle the 'react' npm package with our bundle.js
    //but get it from a global 'React' variable
    'react': 'React'
},
resolve: {
    extensions: ['', '.js', '.jsx']
}
}

Upvotes: 3

Views: 8083

Answers (1)

Sia
Sia

Reputation: 9212

If that is an exact copy of your code, then I think you referenced ReactDOM incorrectly - all the letters in DOM need to be capitalized, like so:

var ReactDOM = require('react-dom');

And in your webpack.config.js externals:

'react-dom': 'ReactDOM'

Note that when setting externals, Webpack expects you to load those libraries separately. For example, by putting a script tag in your HTML (index.html) pointing to the CDN's to react and react-dom or to the internal copies of those two libraries. So, that could also be why you are having issues.

If you want to use the version of React and ReactDOM that came with your node modules, leave out the externals setting for Webpack. It will bundle React and ReactDOM with your own script (making the bundle.js longer), but it will work. From what I can tell, there are a few other ways of handling this (like using Express to expose the relevant files from your node modules), but it seems many people simply bundle them together.

Upvotes: 6

Related Questions