webpack React

React + webpack

Last post, I introduced how to use webpack. webpack Get Started
Next is build React app with webpack.
There are a lot of blogs to mention about it, some are quite complicated.
So I tried very simple one.

Install dependencies

React and webpack

npm install --save react react-dom
npm install --save-dev webpack

babel

npm install --save-dev babel-loader babel-core
npm install --save-dev babel-preset-react
npm install --save-dev babel-preset-es2015

Project

project
|- src
|   |- index.jsx
|- index.html
|-.babelrc
|- webpack.config.js

.babelrc

Prepare babel setting(.babelrc

{
  'presets': ['react', 'es2015']
}

webpack.config.js

module.exports = {
    entry: './src/index.jsx',
    output: {
        path: './dist',
        filename: 'bundle.js'
    },
    devtool: 'inline-source-map',  /* source map */
    module: {
        loaders: [
            {
                test: /\.jsx$/, // Target files
                exclude: /node_modules/, // excludes
                loader: 'babel-loader'
            }
        ]
    }
};

index.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>React and Webpack</title>
</head>

<body>
<div id="content"></div>
<script src="./dist/bundle.js"></script>
</body>

</html>

Import just only one bundle.js

index.jsx

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

// ES2015
// import React from 'react';
// import ReactDOM from 'react-dom';

var Hello = React.createClass({
   render: function() {
       return (
         <div>Hello React and Webpack!</div>
       );
   }
});

ReactDOM.render(
    <Hello/>,
    document.getElementById("content")
);

build

webpack

build for production

Prepare another build setting for Production.
For production, we need more configuration, for example, uglify, compress etc…
Add webpac-production.config.js to your project.
Any name is O.K. we change config file from command

How to build

webpack --config webpack-production.config.js --progress

Add –config option to select config file.

If you want to run from npm, please add script description
package.json

{
  "scripts": {
     "build": "webpack --config webpack-production.config.js --progress"
  }
}