# 二.文件列表插件

# 安装

package.json

{
  "name": "2.plugin",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0"
  },
  "dependencies": {
    "html-webpack-plugin": "^3.2.0"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 文件

plugins/FileListPlugin.js

class FileListPlugin {
  constructor({ filename }) {
    this.filename = filename
  }
  apply(compiler) {
    compiler.hooks.emit.tap("FileListPlugin", (compilation) => {
      // console.log(compilation.assets);
      let assets = compilation.assets
      let content = `## 文件名   资源大小 \r\n`
      Object.entries(assets).forEach(([filename, stateObj]) => {
        content += `- ${filename}  ${stateObj.size()} \r\n`
      })
      assets[this.filename] = {
        source() {
          return content
        },
        size() {
          return content.length
        },
      }
      console.log(content)
    })
  }
}
module.exports = FileListPlugin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

src/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body></body>
</html>
1
2
3
4
5
6
7
8
9
10

src/index.js

console.log(1111111111)
1

# 配置

webpack.config.js

let path = require("path")
let HtmlWebpackPlugin = require("html-webpack-plugin")
let FileListPlugin = require("./plugins/FileListPlugin")
module.exports = {
  mode: "development",
  entry: "./src/index.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
    }),
    new FileListPlugin({
      filename: "list.md",
    }),
  ],
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 打包

npx webpack
1

dis 目录下 list.md:

## 文件名   资源大小
- bundle.js  3883
- index.html  330
1
2
3

完整代码 (opens new window)