插件的环境
- 插件没有像 loader 有独立的运行环境(loader-runner)
- 只能在 webpack 里面运行
loader 是编译过程中,对文件内容进行转换、翻译。 插件则伴随整个 webpack 构建的生命周期,从初始化到文件生成。 loader 没法做的事情,可考虑用 插件 来做
插件使用简介
插件如何获取参数
插件的错误处理
通过 Compilation 进行文件写入
Compilation 上的 assets 可以用于文件写入
- 可以将 zip 资源包设置到 compilation.assets 对象上
文件写入需要使用 webpack-sources
插件扩展:编写插件的插件
开始自定义插件
开发一个压缩构建资源为 zip 包的插件
- 生成的 zip 包文件名称可以通过插件传入
- 需要使用 compiler 对象上的特定 hooks 进行资源生成
使用 jszip 包
const JSZip = require('jszip');const path = require('path');const { RawSource } = require('webpack-sources')const zip = new JSZip();class ZipPlugin {constructor(options) {this.options = options;}checkOptions() {if (!this.options.name) throw new Error("ZipPlugin's options need name")}apply(compiler) {this.checkOptions();compiler.hooks.emit.tapAsync('ZipPlugin', (compilation, callback) => {const folder = zip.folder(this.options.name);for (let filename in compilation.assets) {const source = compilation.assets[filename].source();folder.file(filename, source);}zip.generateAsync({ type: 'nodebuffer' }).then(content => {const outputPath = path.join(compilation.options.output.path,this.options.name + '.zip');const outputRelativePath = path.relative(compilation.options.output.path, outputPath);compilation.assets[outputRelativePath] = new RawSource(content);callback();})})}}module.exports = ZipPlugin;
