Skip to main content

Module Bundling 101 with Webpack

August 18, 2015

Webpack is a module bundler that crawls your dependency graph, applies transforms, and emits one or more bundles ready for the browser. Docs

Why bundle?

  • Resolve import / require() at build‑time so browsers get plain scripts.
  • Combine many files into fewer HTTP requests which speeds up first load.
  • Transform code with loaders (e.g. Babel turns ES6 → ES5, Sass → CSS, images → base64).
  • Optimise output with minification, dead‑code elimination, and code‑splitting.
  • Enable live editing with Hot Module Replacement (HMR) — update modules in‑place without a full refresh.

Key terms

| Term | Purpose | |-----------|--------------------------------------------------------------| | Entry | Starting file for building the dependency graph | | Output | Where Webpack writes the final bundle files | | Loader | Function that transforms matched file types during the build | | Plugin | Hook that extends Webpack (minification, env vars, etc.) | | Dev Server| Memory‑only server that serves bundles and supports HMR | | HMR | Runtime patching of changed modules without page reload |

Project structure

my-app/
├─ src/
│  ├─ index.js
│  └─ message.js
├─ dist/
└─ webpack.config.js

Install Webpack 1 and Babel

# Initialise package.json
npm init -y

# Core bundler and dev server
npm install --save-dev webpack@1 webpack-dev-server@1

# Transpile ES6 to ES5
npm install --save-dev babel-core babel-loader babel-preset-es2015

Create a .babelrc:

{
  "presets": ["es2015"]
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',

  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      }
    ]
  },

  devServer: {
    static: 'dist',
    inline: true,
    hot: true
  }
};

Demo code

src/index.js

import message from './message';

document.body.innerHTML = `<h1>${message}</h1>`;

src/message.js

export default 'Hello, Webpack!';

Build and run

# Production bundle
webpack --mode production

# Development server with hot‑reload
webpack-dev-server --hot --open

Open the local URL printed in the terminal, edit src/message.js, and watch HMR update the page instantly.


Recent posts