import type { Plugin } from 'vite'; /** * 创建开发模式专用的条件插件 * 通过检查模块 ID 来决定是否应用插件 * @param plugin - 要包装的插件 * @param shouldApply - 判断是否应用的函数,接收模块 ID */ export function createDevConditionalPlugin(plugin: Plugin, shouldApply: (id: string) => boolean): Plugin { if (!plugin || typeof plugin !== 'object') { return plugin; } return { ...plugin, name: `dev-conditional:${plugin.name}`, // 在 transform 阶段检查 transform(code: string, id: string) { // 如果不应该应用此插件,直接返回 null if (!shouldApply(id)) { return null; } // 否则调用原插件的 transform if (typeof plugin.transform === 'function') { return plugin.transform.call(this, code, id); } return null; }, // 在 transformIndexHtml 阶段检查 transformIndexHtml(html: string, ctx: any) { // 检查当前处理的 HTML 文件路径 const htmlPath = ctx.filename || ctx.path || ctx.originalUrl || ''; // 如果是简化入口的 HTML,跳过此插件 if (htmlPath.includes('floating-list-window') || htmlPath.includes('popup-window')) { return html; } // 主入口或其他情况,调用原插件的 transformIndexHtml if (typeof plugin.transformIndexHtml === 'function') { return plugin.transformIndexHtml.call(this, html, ctx); } return html; }, // 在 resolveId 阶段检查 resolveId(source: string, importer: string | undefined, options: any) { // 如果导入者是简化入口,跳过此插件 if (importer && !shouldApply(importer)) { return null; } // 否则调用原插件的 resolveId if (typeof plugin.resolveId === 'function') { return plugin.resolveId.call(this, source, importer, options); } return null; }, // 在 load 阶段检查 load(id: string) { if (!shouldApply(id)) { return null; } if (typeof plugin.load === 'function') { return plugin.load.call(this, id); } return null; }, }; } /** * 判断模块是否为主入口(非 other_pages) */ export function isMainEntry(id: string): boolean { // 排除 other_pages 目录下的所有文件 if (id.includes('other_pages') || id.includes('floating-list-window') || id.includes('popup-window')) { return false; } return true; }