Webpack

JavaScript 模块打包器 - 代码分割、加载器、插件构建复杂流水线

TL;DR

是什么:现代 JavaScript 应用的静态模块打包器。

为什么用:打包资源、转换代码、优化构建、丰富的插件生态。

Quick Start

安装

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

创建文件

src/index.js:

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

src/greeting.js:

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

构建

npx webpack

输出将在 dist/main.js

Cheatsheet

命令描述
npx webpack构建(生产)
npx webpack --mode development构建(开发)
npx webpack serve开发服务器
npx webpack --watch监听模式

基础配置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

非 JS 文件需要 Loader

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

开发服务器

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

HTML 插件

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

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

Next Steps