Learn react on railsSort Order

React: Webpack From Scratch

In this episode we show you how to setup webpack, with a basic configuration file. Webpack is a tool that will help us build our bundle for development and production environment.

Project Setup

We begin by installing node. On macOS we simply use homebrew

brew install node

Once we install node we will have access to npm. To generate a project using npm simply do the following in your project directory.

npm init .

The command will initialize your npm project. Simply follow the instructions and you will get a package.json in your project folder.

{  "name": "hello-react",  "version": "1.0.0",  "description": "bootstrap app for react",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "author": "",  "license": "MIT"}


The next thing we need to do is setup webpack. To do this we use the following command.

npm install webpack webpack-dev-server --save-dev

The command above is going to setup webpack and webpack-dev-server for us. The webpack-dev-server package is going to allow us to run a development server that will serve our webpack bundle.

To test webpack lets create a basic index.html in our project with the following content.

<html>  <head>    <meta charset="utf-8">  </head>  <body>    <script type="text/javascript" src="bundle.js" charset="utf-8"></script>  </body></html>

We will also need the javascript to go with it. So go ahead and create the entry.js with the following content.


To compile our script simply run the following.

webpack ./entry.js bundle.js

Load up index.html in the browser and you will see the output from the entry.js file.

Config file for Webpack

The next thing we'll need to do is setup the config file for webpack.

Webpack has the concept of loaders. First we need to install 2 loaders to allow webpack to compile .css files.

npm install css-loader style-loader --save-dev

Go ahead and create a webpack.config.js in our project folder with the following content.

module.exports = {  entry: "./entry.js",  output: {    path: __dirname,    filename: "bundle.js"  },  module: {    loaders: [      { test: /\.css$/, loader: "style!css" }    ]  }};

We can now process css files in our project so lets create one. Go ahead and create a style.css in the project directory.

body {  background: yellow;}

We still need to setup the babel transpiler so we can use next generation javascript in our project. Check out the next episode on how to use the babel transpiler in our project.

Become a member and get access to all member exclusive videos.