Module Bundling 101 with Webpack

Luiz TanureLuiz Tanure
2 min read

Note: This article was originally published on August 18, 2015. Some information may be outdated.

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

TermPurpose
EntryStarting file for building the dependency graph
OutputWhere Webpack writes the final bundle files
LoaderFunction that transforms matched file types during the build
PluginHook that extends Webpack (minification, env vars, etc.)
Dev ServerMemory‑only server that serves bundles and supports HMR
HMRRuntime 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.



Originally published at letanure.dev

0
Subscribe to my newsletter

Read articles from Luiz Tanure directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Luiz Tanure
Luiz Tanure