In last article I built a simple Travel Plan web app with React. All Javascript code were wrote directly inside script tag. In this article I will use webpack to bundle my front end resources.
package.json
First we need to install Node.js and run npm init to generate package.json file. (Refer to npm Docs for details.){:target=”_blank”} This file will keep our dependencies. We won’t add node_modules folder into repository. Whenever we start a new project, run npm install to generate our dependencies. We then use npm install --save react react-dom to install all our project dependencies and npm install --save-dev webpack babel-core babel-loader babel-preset-react style-loader css-loader to install dev dependencies. We add "start": "webpack --progress --colors --watch" in scripts. So we can run npm start to start webpack.
webpack.config.js
webpack will use this config file by default. We add two loaders: one for JSX translation, the other to require css within js.
Components
We split all components(Place, PlaceList, PlaceForm, PlaceBox) into 4 separate files and use modules.exports to export our components and require to include required libraries which uses CommonJS module system.
entry: index.js
With require('./style.css'); Webpack will include the css file into js file which will in turn generate a style tag inside html head and put all the css there.
index.html
webpack will bundle all our js files into bundle.js. So we only need to include one js file here.
npm start
Run npm start to bundle our project. Then you can open index.html file in your browser to check the result.