Search code examples
viterollup

How to exclude `*.test.ts` from Vite 5


I'm using Vite 5. I want to exclude my *.test.ts files from bundling by Vite5.

Here is my vite.config.js:

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";

// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
    const prod = mode === "prod";

    return {
        plugins: [react(), dts(), tsconfigPaths()],
        build: {
            lib: {
                entry: resolve(__dirname, "./src/App.tsx"),
                formats: ["es"],
            },
            rollupOptions: {
                external: [
                    "react",
                    "react-dom",
                ],
            },
            sourcemap: !prod,
        },
    };
});

I've tried:

  • rollupOptions.external: ["**.test.ts"]
  • rollupOptions.external: [src => src.indexOf("*.test.ts") !== -1]

but it doesn't work.

How can I exclude that files?


Solution

  • My problem was that temp.test.d.ts file was included in dist/. I thought it because of Vite bundling option. However it's not a problem about Vite but dts plugin. (Because creating d.ts file is dts's responsibility)

    So I solved it by changing the config to:

    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";
    
    // https://vitejs.dev/config/
    export default defineConfig(({mode}) => {
        const prod = mode === "prod";
    
        return {
            plugins: [react(), dts({exclude: "**/*.test.ts"}), tsconfigPaths()], // the key change is here
            build: {
                lib: {
                    entry: resolve(__dirname, "./src/App.tsx"),
                    formats: ["es"],
                },
                rollupOptions: {
                    external: [
                        "react",
                        "react-dom",
                    ],
                },
                sourcemap: !prod,
            },
        };
    });