14:54:11.857 C:\Users\刘朝旭\Desktop\新项目h5端\App\App\node_modules\unplugin\dist\index.js:1118 14:54:11.861 const onLoadFilter = ((_b = plugin.esbuild) == null ? void 0 : _b.onLoadFilter) ?? /.*/;
时间: 2025-06-24 18:40:07 浏览: 11
### 关于 Unplugin 和 Esbuild 的 `onLoadFilter` 实现
Unplugin 是一种用于构建工具的插件标准,支持多种构建工具(如 Vite、Webpack、Rollup 等),同时也兼容 Esbuild。在使用 Unplugin 配合 Esbuild 时,`onLoadFilter` 是一个重要的配置项,它决定了哪些文件会被加载器处理。
#### `onLoadFilter` 的作用
`onLoadFilter` 是一个函数或正则表达式,用于过滤需要被 `onLoad` 方法处理的文件路径。如果返回值为真,则该文件会触发 `onLoad` 处理逻辑;否则不会进入此流程[^2]。
以下是基于官方文档和社区实践的一个典型实现:
```javascript
// 示例:定义一个简单的 on_Load 过滤器
const onLoadFilter = (id) => /\.custom$/i.test(id);
module.exports = {
name: 'example-unplugin',
setup(build) {
build.onLoad({ filter: onLoadFilter }, async (args) => {
const content = await readFile(args.path, 'utf8');
return { contents: transformContent(content) };
});
},
};
```
在这个例子中,`/\.custom$/i` 正则表达式匹配以 `.custom` 结尾的文件名。只有这些文件才会通过 `onLoad` 流程并调用自定义转换逻辑[^3]。
#### 常见错误及其解决方法
1. **未正确设置 `filter` 参数**
如果 `onLoadFilter` 返回的结果不符合预期,可能会导致某些文件无法正常加载。确保传入的是有效的正则表达式或者布尔值判断逻辑[^4]。
2. **异步操作中的问题**
当 `onLoad` 中涉及异步读取文件或其他资源时,如果没有正确处理 Promise 或者抛出了异常,可能导致整个构建失败。建议始终捕获可能发生的错误,并提供默认行为作为回退方案[^5]。
3. **性能优化不足**
对大量文件应用复杂的过滤条件会影响构建速度。可以考虑预编译常用的正则模式来提升效率[^6]。
#### 完整代码示例
下面是一个更完整的案例展示如何利用 `onLoadFilter` 来扩展功能:
```javascript
import fs from 'fs/promises';
import path from 'path';
export default function customPlugin(options) {
const onLoadFilter = options.filter || /\.(js|ts)$/;
return {
name: 'esbuild-custom-plugin',
setup(build) {
build.onLoad(
{
filter: typeof onLoadFilter === 'function' ? onLoadFilter : new RegExp(onLoadFilter)
},
async ({ path }) => {
try {
let sourceCode = await fs.readFile(path, 'utf8');
// 自定义修改源码逻辑
if (/special-module/.test(path)) {
sourceCode += '\nconsole.log("This is an injected log statement");';
}
return { contents: sourceCode };
} catch (error) {
console.error(`Failed to load file ${path}:`, error.message);
throw error;
}
}
);
},
};
}
```
这段代码展示了如何动态注入日志语句到特定模块中,同时包含了基本的错误捕捉机制[^7]。
---
阅读全文
相关推荐
















