跪拜 Guibai
← Back to the summary

Webpack Bootstrapping: Three Commands, Five Concepts, One Bundle

Webpack Bundling from 0 to 1: Practical Notes

Author: Kevin666

This article records the complete process of setting up a webpack project from scratch, including the commands used, webpack's core concepts, and bundling principles, with flowcharts to aid understanding.

1. Commands Used from 0 to 1

The whole process requires only three core commands:

# 1. Initialize the project (if there is no package.json)
npm init -y

# 2. Install dependencies (webpack itself + CLI + various loaders + plugins + babel)
npm install webpack webpack-cli babel-loader @babel/core @babel/preset-env css-loader style-loader html-webpack-plugin --save-dev

# 3. Execute bundling
npx webpack

You can also configure a script in package.json and then use npm run build instead of npx webpack:

"scripts": {
  "build": "webpack",
  "dev": "webpack --watch"
}

Memory rhyme: npm install installs things, npx webpack bundles. The rest is a matter of configuration files.

2. Project Structure

webpack-demo/
├── package.json          # Dependencies and scripts
├── webpack.config.js     # Webpack configuration (core)
├── .babelrc              # Babel transpilation configuration
├── index.html            # Template for HtmlWebpackPlugin
└── src/
    ├── index.js          # Entry file
    ├── greet.js          # Module imported by index.js
    └── style.css         # Stylesheet

3. Webpack's Five Core Concepts

Concept Role Configuration Example
entry Where dependency analysis starts entry: './src/index.js'
output Where and under what name the bundle is written output: { path, filename }
loader Lets webpack handle non-JS files (CSS, images, etc.) module.rules
plugin Extends functionality (generates HTML, compresses, cleans, etc.) plugins: [...]
mode development does not compress / production compresses and optimizes mode: 'development'

4. Webpack Bundling Flow

Webpack's bundling process can be summarized with a flowchart:

image.png

In short: webpack starts from the entry, recursively finds all dependencies along import statements, uses the appropriate loaders to translate non-JS files into forms JavaScript understands, and finally merges everything into one or more bundle files for output.

5. Difference Between Loaders and Plugins

Loader

Responsible for translating files. Webpack itself only understands JS; when it encounters .css, .png, .ts files, loaders convert them into modules.

Examples: css-loader, babel-loader, ts-loader

Plugin

Responsible for miscellaneous tasks, extending webpack's capabilities. It executes tasks at various lifecycle hooks during bundling, such as generating HTML, cleaning directories, and compressing code.

Examples: HtmlWebpackPlugin, CleanWebpackPlugin

6. Configuration File Explained

This is the webpack.config.js for this project:

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'development',                          // Bundling mode
  entry: './src/index.js',                      // Entry
  output: {                                     // Output
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    clean: true,
  },
  module: {                                     // Loader rules
    rules: [
      { test: /.js$/, exclude: /node_modules/, use: 'babel-loader' },
      { test: /.css$/, use: ['style-loader', 'css-loader'] },
    ],
  },
  plugins: [                                    // Plugins
    new HtmlWebpackPlugin({ template: './index.html' }),
  ],
}

Note the loader execution order: loaders in the use array execute from right to left. For example, when processing CSS, css-loader first parses the CSS, then style-loader injects the styles into the page.

7. Bundled Output

After running npx webpack, the dist/ directory is generated:

dist/
├── bundle.js      # All JS + CSS merged output (24KB)
└── index.html     # Automatically injects <script src="bundle.js">

Open dist/index.html in the browser to see the result. All originally scattered modules (index.js, greet.js, style.css) are bundled into a single bundle.js.

8. Mode Comparison

mode Compressed? Bundle Size Use Case
development No Larger (~24KB) Local development, easier debugging
production Yes Much smaller (a few KB) Deployment to production

Summary

  1. Webpack is essentially a module bundler; it starts from the entry, recursively collects all dependencies, and merges them into a bundle.
  2. Webpack itself only understands JS; other files are handled by loaders for translation, while plugins extend functionality.
  3. Five core concepts: entry, output, loader, plugin, mode.
  4. The daily commands are two: npm install installs dependencies, npx webpack bundles.

Master these, and you can understand the bundling configuration of most front-end projects.