1

I'm using Webpack to bundle my ReactJS application.

helloworld.js

import React from 'react';

export default class HelloWorld extends React.Component {
    render() {
        return <h2>Hello {this.props.name}!</h2>;
    }
}

index.js

import ReactDOM from 'react-dom';
import HelloWorld from './helloworld';

ReactDOM.render(<HelloWorld name="World" />,
    document.getElementById('container'));

webpack.config.js

module.exports = {
    entry: './index.js',
    output: 'bundle.js',
    module: {
        loaders: [
            {
                test: /(\.js|\.jsx)/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};

When I run webpack-dev-server --progress --colors I'm getting an error in the browser "React is not defined" but if I import React directly in the index.js then the error not comes. Why Webpack is not including React in the bundle if it is referenced in the helloworld.js file?

2 Answers 2

1

Well webpack only tries to bundle up the individual modules by reading the dependencies in it and resolving them to render a particular element. Now while bundling

ReactDOM.render(<HelloWorld name="World" />,
    document.getElementById('container'));

ReactDOM tries to execute React.createElement(_Helloworld2.default, { name: 'World' }), document.getElementById('app') function which requires React as a dependency that is not present in your index.js file so it gives an error and solve the issue when you import React in your index.js file. I hope I was able to explain and my answer helps you.

Sign up to request clarification or add additional context in comments.

Comments

1

You are missing import React from 'react'; statement. You will need it every time You write some JSX in a file, because it is transformed into React.createElement(..) function calls.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.