You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vite 5中排除*.test.ts文件参与打包?

如何在Vite 5中排除*.test.ts文件打包

你之前尝试的两种配置方式存在问题:

  • ["**.test.ts"] 的glob模式格式错误,正确写法应为 **/*.test.ts
  • src => 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:13:00