如何为自定义 Plugin 添加配置项并支持用户传参?
解读
面试官问的不是“plugin 怎么用”,而是“你写的 plugin 怎么让别人用”。
在国内一线/二线大厂的面试里,这道题通常出现在“工程化方向”二面或三面,用来区分“只会配 webpack”与“能造轮子”的候选人。
核心考察点:
- 是否理解 Webpack 插件的“构造函数收参 + 校验 + 默认值”三板斧;
- 是否能在不破坏插件实例单例的前提下,把用户配置安全地注入到钩子中;
- 是否考虑到了国内最常见的三种接入场景:
- 业务线直接 new Plugin({...});
- 基于 @vue/cli、umi、modern.js 等框架的 preset 二次封装;
- 微前端/Monorepo 里被不同子应用复用,需要“配置合并”与“环境隔离”。
答得漂亮,可以顺势把“插件单元测试”、“schema-utils 校验”、“typescript 声明文件”全部展开,直接拿到“工程化专家”评级。
知识点
- 插件形态:class 必须带 apply(compiler) 方法,compiler 是 Webpack 启动后生成的单例。
- 参数通道:用户通过 new Plugin(options) 把配置传进构造函数,插件内部用 this.options 缓存。
- 默认值与合并:Object.assign 或 lodash.merge,注意不能修改用户传入的原始对象,防止跨编译实例污染。
- 参数校验:schema-utils 对 options 做 JSON-Schema 校验,失败时通过 compiler.getInfrastructureLogger 抛出 Error,Webpack 会在 compilation 阶段统一收集并打印成红色 fatal 日志。
- 多钩子消费:同一插件可能在 emit、afterEmit、done 等多个阶段读取 this.options,必须保证只读。
- 热更新兼容:devServer 模式下插件会被反复实例化,不要把副作用写在模块顶层,而是放在钩子内部。
- 国内特殊场景:
- 公司私有 npm 源,插件包名以 @company 开头,需要在 README 给出 cnpm 安装示例;
- 很多项目仍用 Webpack4,插件若用到 Webpack5 的 thisCompilation 钩子,需要判断 compiler.webpack.version 并降级;
- 有些老项目把配置写在 vue.config.js 的 chainWebpack 里,要求插件支持“函数式配置”——即 options 也可以是一个 (config, env) => options 的函数。
答案
- 定义插件骨架
// src/index.js
const { validate } = require('schema-utils');
const schema = {
type: 'object',
properties: {
filename: { type: 'string', minLength: 1 },
include: { instanceof: 'RegExp' },
exclude: { instanceof: 'RegExp' },
},
additionalProperties: false,
};
const PLUGIN_NAME = 'ExtractStatsPlugin';
class ExtractStatsPlugin {
constructor(options = {}) {
// 1. 缓存用户配置
this.options = Object.assign(
{
filename: 'stats.json',
include: /\.(js|mjs|jsx)$/,
exclude: /node_modules/,
},
options
);
// 2. 参数校验
validate(schema, this.options, { name: PLUGIN_NAME });
}
apply(compiler) {
const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
compiler.hooks.emit.tapAsync(PLUGIN_NAME, (compilation, callback) => {
const { filename, include, exclude } = this.options;
const stats = {};
for (const [pathname, asset] of Object.entries(compilation.assets)) {
if (!include.test(pathname) || exclude.test(pathname)) continue;
stats[pathname] = asset.size();
}
const content = JSON.stringify(stats, null, 2);
compilation.assets[filename] = {
source: () => content,
size: () => content.length,
};
logger.info(`✅ ${filename} 已生成,共 ${Object.keys(stats).length} 条记录`);
callback();
});
}
}
module.exports = ExtractStatsPlugin;
- 使用示例
// webpack.config.js
const ExtractStatsPlugin = require('extract-stats-plugin');
module.exports = {
plugins: [
new ExtractStatsPlugin({
filename: 'report/stats.json',
include: /\.js$/,
exclude: /vendor/,
}),
],
};
- 单元测试(jest 快照)
const { createCompiler } = require('@webpack/test-utils');
const ExtractStatsPlugin = require('../src');
test('should output stats.json', async () => {
const compiler = createCompiler({
entry: { main: './fixtures/a.js' },
plugins: [new ExtractStatsPlugin({ filename: 'test.json' })],
});
const { assets } = await compiler.run();
expect(assets['test.json'].source()).toMatchSnapshot();
});
- TypeScript 声明(国内很多团队用 TS,不写声明会被吐槽)
// types.d.ts
export interface Options {
filename?: string;
include?: RegExp;
exclude?: RegExp;
}
declare class ExtractStatsPlugin {
constructor(options?: Options);
apply(compiler: import('webpack').Compiler): void;
}
export = ExtractStatsPlugin;
拓展思考
-
动态配置:如果插件需要“读环境变量 + 读 webpack 配置”再做二次计算,可以把 options 设计成函数
new Plugin((env, webpackConfig) => ({ filename:${env}-stats.json}))
在构造函数里执行 const opts = typeof options === 'function' ? options(process.env, compiler.options) : options; 即可。 -
配置继承:Monorepo 里根目录已有默认配置,子包只想改 filename,可以用 webpack-merge 做 deep merge,并在插件里暴露静态方法
ExtractStatsPlugin.merge = (defaultOpts, userOpts) => merge(defaultOpts, userOpts); -
性能兜底:插件若遍历 compilation.modules,务必加 cacheStage = compilation.getCache(PLUGIN_NAME) 并使用 compilation.fileSystemInfo.getDeprecatedFileHash,否则在 Webpack5 持久化缓存下会触发全量重编译,CI 构建时长翻倍,容易被国内“构建性能小组”打回。