安装

下面均已 webpack5 为例

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

运行命令

可以使用 webpack 初始化命令快速生成一个项目

npx webpack-cli init

以下是自动生成的webpack.config.js

// Generated using webpack-cli https://github.com/webpack/webpack-cli

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const isProduction = process.env.NODE_ENV == "production";

const stylesHandler = isProduction
    ? MiniCssExtractPlugin.loader
    : "style-loader";

const config = {
    entry: "./src/index.js",
    output: {
        path: path.resolve(__dirname, "dist"),
    },
    devServer: {
        open: true,
        host: "localhost",
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "index.html",
        }),

        // Add your plugins here
        // Learn more about plugins from https://webpack.js.org/configuration/plugins/
    ],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/i,
                loader: "babel-loader",
            },
            {
                test: /\.css$/i,
                use: [stylesHandler, "css-loader"],
            },
            {
                test: /\.s[ac]ss$/i,
                use: [stylesHandler, "css-loader", "sass-loader"],
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
                type: "asset",
            },

            // Add your rules for custom modules here
            // Learn more about loaders from https://webpack.js.org/loaders/
        ],
    },
};

module.exports = () => {
    if (isProduction) {
        config.mode = "production";

        config.plugins.push(new MiniCssExtractPlugin());
    } else {
        config.mode = "development";
    }
    return config;
};

也可以手动新建一个 webpack.config.js 文件手动配置
可以配置 npm run script 命令运行 webpack,也可以手动 npx webpack xxx 运行

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode=production --node-env=production",
    "build:dev": "webpack --mode=development",
    "build:prod": "webpack --mode=production --node-env=production",
    "watch": "webpack --watch",
    "serve": "webpack serve"
  },

入口

入口可以是一个文件或多个 js 文件

module.exports = {
    //...
    entry: {
        home: "./home.js",
        about: "./about.js",
        contact: "./contact.js",
    },
};

https://webpack.docschina.org/configuration/entry-context/#entry

输出

设置输出的文件,设置clean: true输出前先清空输出目录

    output: {
        filename: "[name].[contenthash].js",
        path: path.resolve(__dirname, "dist"),
        clean: true,
    },

可以用多种方式设置输出文件的名称
https://webpack.docschina.org/configuration/output/#outputfilename

加载 html 模板

使用html-webpack-plugin插件

const HtmlWebpackPlugin = require("html-webpack-plugin");
plugins: [
    new HtmlWebpackPlugin({
        template: "./src/index.html",
        filename: "index.html",
    }),
];

加载 CSS

需要先 npm 安装相应包,sass-loader将 sass 文件转换为 css 文件,css-loader加载 css 文件,style-loader将 css 文件通过 js 的方式将 css 加载到页面中。

module: {
    rules: [
        {
            test: /\.s[ac]ss$/i,
            use: ["style-loader", "css-loader", "sass-loader"],
        },
    ],
},

如果要分离 css 文件,可以使用MiniCssExtractPlugin,会自动 link 到 HtmlWebpackPlugin 中

const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
//...
    {
        test: /\.s[ac]ss$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
    },
//...
    plugins: [
    new HtmlWebpackPlugin({
        template: "./src/index.html",
        filename: "index.html",
    }),
    new MiniCssExtractPlugin({
        filename: "style.min.css",
    }),
],

加载静态文件

webpack5 使用asset-modules模块来管理静态文件
https://webpack.docschina.org/guides/asset-modules/

环境分离

使用webpack-merge模块实现生产开发环境分开设置
https://webpack.docschina.org/guides/production/

开发环境设置

设置 devtool 使用 source map https://webpack.docschina.org/configuration/devtool/
设置热更新

devServer: {
    contentBase: "./dist",
    hot: true,
},

参考

https://webpack.docschina.org/guides/getting-started/
https://www.lookroot.cn/course/webpack/
https://szxio.gitee.io/hexoblog/Tool/webpack/

最后修改:2021 年 08 月 22 日
你的赞赏是我前进的动力