Webpack

Module bundler for JavaScript - code splitting, loaders, plugins for complex build pipelines

TL;DR

What: A static module bundler for modern JavaScript applications.

Why: Bundle assets, transform code, optimize builds, extensive plugin ecosystem.

Quick Start

Install:

npm init -y
npm install webpack webpack-cli --save-dev

Create files:

src/index.js:

import { greeting } from './greeting.js';
console.log(greeting('World'));

src/greeting.js:

export function greeting(name) {
  return `Hello, ${name}!`;
}

Build:

npx webpack

Output will be in dist/main.js

Cheatsheet

CommandDescription
npx webpackBuild (production)
npx webpack --mode developmentBuild (development)
npx webpack serveDev server
npx webpack --watchWatch mode

Basic config (webpack.config.js):

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  mode: 'development',
};

Gotchas

Loaders for non-JS files

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|jpg|gif)$/,
        type: 'asset/resource',
      },
    ],
  },
};

Dev server

npm install webpack-dev-server --save-dev
module.exports = {
  devServer: {
    static: './dist',
    hot: true,
    port: 3000,
  },
};

HTML plugin

npm install html-webpack-plugin --save-dev
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
  ],
};

Next Steps