React App with Webpack

07/02/2018 erbileren
The estimated reading time for this post is 2 minutes

The previous post (Create a React App from Scratch) covers how you create a react project. In this section, we will add webpack to our react project and run it.

First, we start with installing webpack packages:

npm install --save webpack webpack-dev-server

The webpack helps us to bundle javascript code, and the webpack-dev-server runs the code in the development server.

After the installation, we need to create a configuration file. To do this let’s started with creating a new folder in the project’s root directory and create a configuration file in this file:

mkdir webpack
cd webpack

We need to fill file with following lines:

// let's started with importing webpack
var webpack = require('webpack');

// paretDir helps us to point the parent directory
var path = require('path');
var parentDir = path.join(__dirname, '../');

module.exports = {
    // We need to define the entry point which is index.js for our project
    entry: [
        path.join(parentDir, 'index.js')
    // loaders are responsible to bundle source files
    module: {
        loaders: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            loader: 'babel-loader'
        }, {
            test: /\.(css|less)$/,
            loaders: ["style-loader", "css-loader", "less-loader"]
    // We nedd to tell where the output file, bundle.js, is located
    output: {
        path: parentDir + '/dist',
        filename: 'bundle.js'
    // Last step is define options for the development server
    devServer: {
        contentBase: parentDir,
        historyApiFallback: true

The last thing we need to do is add npm script to the package.json file.

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "dev": "./node_modules/.bin/webpack-dev-server --config ./webpack/"

Let’s try our app. In your console just type this:

npm run dev

and go to http://localhost:8080 using your browser.

As usual you can find the entire source codes on Github:

, , ,

Comment (1)

Leave a Reply

Your email address will not be published. Required fields are marked *