1、html-webpack-plugin

当我们根据功能或者模块将代码分成多个js,这时候利用webpack会输出多个bundle。index.html需要手动引入多个bundle会变得困难。这时候可以通过设置HtmlWebpackPlugin来实现多个bundle的自动化引入。

npm install --save-dev html-webpack-plugin
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  mode: 'production',
  entry: {
    app: "./src/index.js",
    print: "./src/print.js"
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: '管理输出'
    })
  ],
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
}

1、下载html-webpack-plugin,并引入

2、在entry中定义多个入口,同时output的filename设置为`[name].bundle.js``,这样可以使打包生成的bundle名称分别为app.bundle.js、print.bundle.js。否则执行打包命令会报错出现多个重名的bundle。

3、plugins中使用html-webpack-plugin,这里上面声明的HtmlWebpackPlugin是一个构造函数,需要通过new HtmlWebpackPlugin({...})使用。html-webpack-plugin可以动态生成index.html并且动态引入entry中定义的文件。

Q1:使用html-webpack-plugin报错 Cannot read property 'tap' of undefined。

查看自己webpack版本是否与html-webpack-plugin版本一致。自己项目中webpack用的4+,则html-webpack-plugin也用4+。

2、clean-webpack-plugin

clean-webpack-plugin负责清理/dist文件夹

经过webpack打包后,生成文件会被输出到output定义的path中。有些打包文件在项目开发过程中已经不需要了,但是webpack本身不具有自动清理/dist的功能。这时候需要clean-webpack-plugin

const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: {
    app: "./src/index.js",
    print: "./src/print.js",
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: '管理输出'
    })
  ],
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      }
    ],
  },
};

3、manifest

描述模块与所生成的bundle之间的映射关系。可以使用webpack-manifest-plugin将mainfest数据提取为到json文件中。

npm install webpack-nano webpack-manifest-plugin --save-dev
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');

module.exports = {
  mode: 'production',
  entry: {
    app: "./src/index.js",
    print: "./src/print.js",
    // test: "./src/test.js"
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: '管理输出'
    }),
    new WebpackManifestPlugin()
  ],
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
}

所生成的mainfest.json文件