AnalyzeWebpackPlugin作用:分析 webpack 打包资源大小,并输出分析文件 .mdZ格式
什么时候执行:
compiler.hooks.emit
, 它是在打包输出前触发,我们需要分析资源大小同时添加上分析后的 md 文件
1. 遍历所有即将输出文件,得到其大小
2、生成一个md文件
class AnalyzeWebpackPlugin {
apply(compiler) {
compiler.hooks.emit.tap("AnalyzeWebpackPlugin", (compilation) => {
// 1. 遍历所有即将输出文件,得到其大小
/*
将对象变成一个二维数组:
对象:
{
key1: value1,
key2: value2
}
二维数组:
[
[key1, value1],
[key2, value2]
]
*/
const assets = Object.entries(compilation.assets);
/*
md中表格语法:
| 资源名称 | 资源大小 |
| --- | --- |
| xxx.js | 10kb |
*/
let content = `| 资源名称 | 资源大小 |
| --- | --- |`;
assets.forEach(([filename, file]) => {
content += `\n| ${filename} | ${Math.ceil(file.size() / 1024)}kb |`;
});
// 2. 生成一个md文件
compilation.assets["analyze.md"] = {
source() {
return content;
},
size() {
return content.length;
},
};
});
}
}
module.exports = AnalyzeWebpackPlugin;
webpack配置使用
const AnalyzeWebpackPlugin = require("./plugins/analyze-webpack-plugin");
new AnalyzeWebpackPlugin(),
const path = require("path");
//处理html
const HtmlWebpackPlugin = require("html-webpack-plugin");
//插件需要先引入再使用
const TestPlugin = require("./plugins/test-plugin2");
const BannerWebpackPlugin = require("./plugins/banner-webpack-plugin");
const CleanWebpackPlugin = require("./plugins/clean-webpack-plugin");
const AnalyzeWebpackPlugin = require("./plugins/analyze-webpack-plugin");
module.exports = {
entry: "./src/main.js",//根据找到依赖
output: {
path: path.resolve(__dirname, "./dist"),
filename: "js/[name].js",// filename: 输出文件名
//clean: true,
},
module: {//编译记载配置
rules: [
// {
// test: /\.js$/,//处理js文件
// loader: "./loaders/test-loader.js",//将要处理文件作为参数传到test-loader.js
// },
{
test: /\.js$/,//处理js文件
// use: ["./loaders/demo/test1","./loaders/demo/test2"],
// loader: "./loaders/demo/test3",
// use: ["./loaders/demo/test4","./loaders/demo/test5","./loaders/demo/test6"],
loader: "./loaders/clean-log-loader",
},
{
test: /\.js$/,//处理js文件
loader: "./loaders/banner-loader/index.js",
options:{
author:"老王",
// age:"34"
}
},
{
test: /\.js$/,
loader: "./loaders/babel-loader",
options: {
presets: ["@babel/preset-env"],//传入的预设选项@babel/preset-env
},
},
{
test: /\.(png|jpe?g|gif)$/,
loader: "./loaders/file-loader",
type: "javascript/auto", // 阻止webpack默认处理图片资源,只使用file-loader处理
},
{
test: /\.css$/,
// use: ["style-loader", "css-loader"],
use: ["./loaders/style-loader","css-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "public/index.html"),
}),
//new TestPlugin(),
new BannerWebpackPlugin({
author: "老王",
}),
new CleanWebpackPlugin(),
new AnalyzeWebpackPlugin(),
],
mode: "production",
};