实现FileListPlugin插件

实现FileListPlugin插件

FileListPlugin.js
class FileListPlugin {
    constructor({filename}) {
        this.filename = filename;
    }
    apply(compiler) {
        // 文件已经准备好了,准备发射
        compiler.hooks.emit.tapAsync('FileListPlugin', (compliation, cb) => {
            // console.log(compliation.assets);
            let assets = compliation.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;
                }
            };
            cb();
        })
    }
}

module.exports = FileListPlugin;

webpack.config.js
let webpack = require('webpack');
let path = require('path');
let DonePlugin = require('./plugins/DonePlugin');
let AsyncPlugin = require('./plugins/AsyncPlugin');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let FileListPlugin = require('./plugins/FileListPlugin');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    mode: 'development',
    module: {

    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html"
        }),
        new FileListPlugin({
            filename: 'list.md',
        }),
        new AsyncPlugin(),
        new DonePlugin(),
    ]
}
;

你可能感兴趣的:(webpack系列,FileListPlugin,手写webpack插件,webpack,plugins)