如何在插件中使用 rollup-pluginutils 的 createFilter 工具函数过滤文件?
解读
这道题表面问“怎么用”,实则考察三点:
- 是否知道 Vite 插件与 Rollup 插件共用一套过滤机制;
- 是否理解 createFilter 的“包含/排除”语义与 minimatch 规则;
- 能否把过滤逻辑放在插件生命周期的正确位置,避免无效遍历。
国内面试中,如果只说“我写过 filter”却讲不清 glob 写法、顺序优先级、对性能的影响,会被直接判定为“只抄过文档”。因此,回答必须给出“能跑起来的最小代码 + 讲清原理 + 给出性能提示”。
知识点
- createFilter(include?, exclude?, options?)
- 返回类型:(id: string) => boolean
- include/exclude 支持字符串、数组、正则、函数;字符串默认按 minimatch 解析
- options.resolve 为 false 时,不对 id 做 path.resolve,适合已绝对路径场景
- 过滤位置
- transform、load、resolveId 钩子内最先执行,短路无效文件
- 不要在 config 钩子外反复构造 filter,避免每次调用都新建函数
- Vite 与 Rollup 差异
- Vite 开发时走 esbuild,仅类型声明与 Rollup 一致;生产打包完全由 Rollup 执行,因此 filter 逻辑在两种模式下都要生效
- 国内常见踩坑
- Windows 路径分隔符:minimatch 默认区分 / 与 \,需 ensureUnixPath 或设置 dot: true
- monorepo 子包路径包含 @scope,写规则时容易漏掉 **
- 把 filter 写在闭包外,防止热更新重复创建函数导致内存泄漏
答案
// vite-plugin-strip-console.ts
import type { Plugin } from 'vite';
import { createFilter } from '@rollup/pluginutils';
export default function stripConsole(
options: { include?: string | RegExp | (string | RegExp)[]; exclude?: string | RegExp | (string | RegExp)[] } = {}
): Plugin {
// 1. 在插件初始化阶段只构造一次 filter,避免每次 transform 新建函数
const filter = createFilter(options.include || ['**/*.js', '**/*.ts', '**/*.vue'], options.exclude || 'node_modules/**');
return {
name: 'vite:strip-console',
transform(code, id) {
// 2. 不符合过滤规则的文件直接 return null,交给下一个插件
if (!filter(id)) return null;
// 3. 真正处理逻辑
const stripped = code.replace(/\bconsole\.(log|warn|error)\s*\([^)]*\);?/g, '');
return {
code: stripped,
map: null, // 简单示例,实际可用 magic-string 生成 sourcemap
};
},
};
}
使用方式:
// vite.config.ts
import { defineConfig } from 'vite';
import stripConsole from './vite-plugin-strip-console';
export default defineConfig({
plugins: [
stripConsole({
include: 'src/**',
exclude: ['src/utils/debug.ts', '**/*.d.ts'],
}),
],
});
关键点总结:
- createFilter 在插件最外层执行一次,复用返回函数;
- 过滤失败立即 return null,减少后续无意义的 AST 遍历;
- 字符串规则默认按 minimatch 解析,** 通配多级目录,node_modules/** 必须显式排除;
- 若路径可能含 Windows 反斜杠,先用 normalizePath(id) 转 / 再传 filter,避免匹配失效。
拓展思考
- 性能优化:在大型 monorepo 中,include 数组过长会导致 minimatch 多次执行,可预先把规则编译成正则,或改用 picomatch 的 scan+parse 结果做缓存。
- 与 Vite 内部过滤协同:Vite 本身对 node_modules 做了默认排除,若插件仍需处理第三方包,必须主动把 include 写成 '/node_modules/some-lib/',并在插件名前加上 enforce: 'pre',确保在 Vite 内置插件之前运行。
- 源码安全:国内部分公司要求对 console 进行“脱敏”而非简单删除,可结合 createFilter 做分级处理——开发环境保留、测试环境脱敏、生产环境剔除,通过 define 注入的 MODE 变量动态切换规则。