如何在Vite 5中排除*.test.ts文件参与打包?
如何在Vite 5中排除*.test.ts文件打包
你之前尝试的两种配置方式存在问题:
["**.test.ts"]的glob模式格式错误,正确写法应为**/*.test.tssrc => src.indexOf("*.test.ts") !== -1中的*.test.ts是通配符,但indexOf只会匹配字符串字面量,无法解析通配符,因此无法生效
以下是两种正确的配置方案:
方案一:使用glob模式匹配排除
修改rollupOptions.external为正确的glob路径,同时给dts插件添加排除规则(避免生成test文件的类型声明):
import {defineConfig} from "vite"; import react from "@vitejs/plugin-react"; import dts from "vite-plugin-dts"; import tsconfigPaths from "vite-tsconfig-paths"; import {resolve} from "path"; export default defineConfig(({mode}) => { const prod = mode === "prod"; return { plugins: [ react(), // 排除test文件的类型生成 dts({ exclude: ['**/*.test.ts'] }), tsconfigPaths() ], build: { lib: { entry: resolve(__dirname, "./src/App.tsx"), formats: ["es"], }, rollupOptions: { external: [ "react", "react-dom", // 排除所有.test.ts文件 '**/*.test.ts' ], }, sourcemap: !prod, }, }; });
方案二:使用函数精确匹配排除
如果glob模式不生效,可以用函数判断模块路径是否包含.test.ts,这种方式更灵活:
import {defineConfig} from "vite"; import react from "@vitejs/plugin-react"; import dts from "vite-plugin-dts"; import tsconfigPaths from "vite-tsconfig-paths"; import {resolve} from "path"; export default defineConfig(({mode}) => { const prod = mode === "prod"; return { plugins: [ react(), dts({ exclude: ['**/*.test.ts'] }), tsconfigPaths() ], build: { lib: { entry: resolve(__dirname, "./src/App.tsx"), formats: ["es"], }, rollupOptions: { external: (source) => { // 判断模块是否为test文件 return source.includes('.test.ts') || ["react", "react-dom"].includes(source); }, }, sourcemap: !prod, }, }; });
注意事项
- 如果test文件未被入口文件(
App.tsx)引入,默认不会被打包,但配置排除规则可彻底避免意外引入的情况 - 必须给
dts插件添加exclude配置,否则插件会自动生成test文件的类型声明,导致打包产物包含不必要的类型文件
内容的提问来源于stack exchange,提问作者n8o
相关产品推荐
相关产品推荐

