How To Setup Webpack 2

How To Setup Webpack 2

Published at

Reading time

Webpack is module bundler for modern web applications.

  • It is a highly configurable and easy to use.
  • Reduces the network request by bundling all static assets into a single file.
  • Hot Reloading helps us to forget about the good old gulp and grunt watchers (we won't be talking about this).

Steps

Step 1 - Create a folder

Create a folder called webpack-2-setup and cd into it.

$ mkdir webpack-2-setup && cd webpack-2-setup

Step 2 - Install webpack

$ npm install --save-dev webpack@latest webpack-dev-server@latest

or do it via Yarn.

From now on, I will be using yarn to install our dependencies.

$ yarn add --dev webpack@latest webpack-dev-server@latest

Step 3 - Creating webpack config

Create a webpack.config.js file in the root of our directory and let's write some configuration.

var webpack = require('webpack');

var config = {
  context: __dirname + '/src', // `__dirname` is root of project and `src` is source
  entry: {
    app: './app.js',
  },
  output: {
    path: __dirname + '/dist', // `dist` is the destination
    filename: 'bundle.js',
  },
};

module.exports = config;

Create src/ directory as well. Now lets add lodash to dependencies in package.json by.

$ yarn add --dev lodash

And create a file called app.js in src/ directory.

var _ = require('lodash');

var array = [1];
var other = _.concat(array, 2, [3], [[4]]);

alert(other); // [1, 2, 3, [4]]

Step 4 - Run webpack

To run webpack in development mode, type the following in your terminal.

$ webpack

Screenshot for development mode.

Webpack Devserver

bundle size: 544 KB

To run webpack in production mode, type the following in your terminal.

$ webpack -p
  • -p is for production which uglify and minify the files.
  • bundle.js is our bundled file which is added to dist/ directory.

Screenshot for production mode.

Webpack Production

bundle size: 72.3 KB

We need a local server to run our application. So let's setup a development server.

Step 5 - Setup webpack development server

Webpack has its own development server. Let's add it to the webpack.config.js configuration.

var config = {
  devServer: {
    contentBase: __dirname + '/src', // `__dirname` is root of the project
  },
};

And add the script bundle.js file in src/index.html like below.

<!DOCTYPE html>
<html>
  <head>
    <title>Webpack 2 Setup</title>
  </head>
  <body>
    <!-- bundler script file -->
    <script src="/bundle.js"></script>
  </body>
</html>

Step 6 - Run development server

$ webpack-dev-server

Open http://localhost:8080 in your browser.

Screenshot for development server running in browser.

Browser

More configuration details on webpack-dev-server. That's all, the basic webpack configuration is done.

But what about ES6 support? How to setup that? Let us see.

Loaders

A Loader is a task in webpack, which allows to require() CSS files in javascript or convert an image into data-URLs etc,

We are going to set up ES6 + Babel using a webpack babel loader.

Step 1 - Install babel loader & ES6 preset.

$ yarn add --dev babel-loader babel-core babel-preset-es2015

Now we have to add loader configurations to webpack.config.js file.

Step 2 - ES6 loader

module: {
  rules: [
    {
      test: /\.js$/, // Check for all js files
      exclude: /node_modules/,
      use: [
        {
          loader: 'babel-loader',
          options: { presets: ['es2015'] },
        },
      ],
    },
  ];
}

Now, ES6 syntax is supported, let us check by changing app.js to ES6.

// importing lodash module
import _ from 'lodash';

const array = [1];
const other = _.concat(array, 2, [3], [[4]]);

alert(other); // [1, 2, 3, [4]]

Again run the development server and check.

$ webpack-dev-server

ES6 support is added greatly. But we need a way to debug bundle.js file for development since it will be bundled into a small file. So that means we have to add a sourcemap.

Before adding sourcemap, how do you tell which in mode webpack is running? So for that, we need to an environment for production and development.

Step 7 - Development & Production environment

In package.json file, let's add scripts to run our dev server and production.

"scripts": {
  "start": "webpack-dev-server",
  "build": "NODE_ENV=production webpack -p --config webpack.config.js"
}

By setting NODE_ENV in the build script, we can access it in webpack.config.js and add configurations accordingly.

Step 8 - Sourcemap for development & production

Now we know when we are running for production or development. Let us use it to set up the sourcemap accordingly.

var config = {
  devtool: 'eval-source-map', // Default development sourcemap
};

// Check if build is running in production mode, then change the sourcemap type
if (process.env.NODE_ENV === 'production') {
  config.devtool = ''; // No sourcemap for production

  // Add more configuration for production here like
  // SASS & CSS loaders
  // Offline plugin
  // Etc,
}

module.exports = config;

More information on webpack's sourcemaps.

Final

Below code contains all the configurations for the webpack from above steps.

var webpack = require('webpack');

var config = {
  context: __dirname + '/src', // `__dirname` is root of project and `src` is source

  entry: {
    app: './app.js',
  },

  output: {
    path: __dirname + '/dist', // `dist` is the destination
    filename: 'bundle.js',
  },

  //To run development server
  devServer: {
    contentBase: __dirname + '/src',
  },

  module: {
    rules: [
      {
        test: /\.js$/, // Check for all js files
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: { presets: ['es2015'] },
          },
        ],
      },
    ],
  },

  devtool: 'eval-source-map', // Default development sourcemap
};

// Check if build is running in production mode, then change the sourcemap type
if (process.env.NODE_ENV === 'production') {
  config.devtool = ''; // No sourcemap for production

  // Add more configuration for production here like
  // Uglify plugin
  // Offline plugin
  // Etc,
}

module.exports = config;

That's all. Thanks for reading my article.

Helpful References:

Share this article