Search code examples
typescriptbuildconfigvite

Running vite build using tsconfig.build.ts


Question

Is there a way to specify which tsconfig file to use when running the vite build command?

Problem

I am building a component library with Vite and TypeScript. My test suite is running the new Cypress component testing feature and so I've included "src/**/*.cy.ts" in my tsconfig.json. TypeScript needed some type definitions which I put in cypress/support/components.d.ts, and included "cypress/**/*.ts" in my tsconfig.json. Everything is working as it should, but cypress/support/components.d.ts is included in my dist directory on build.

I've gone through the docs for both Vite and Rollup, but was unable to find a way to exclude Cypress when building. Now I want to simply have a tsconfig.build.json that extends tsconfig.json, but excludes all Cypress related files. The only thing left is to tell Vite that I want to use tsconfig.build.json during the build process.

I imagine this would be done either through vite.config.ts or as a flag (vite build --config tsconfig.build.json).

I made a tsconfig.build.json:

{
  "extends": "./tsconfig.json",
  "exclude": [
    "node_modules",
    "cypress"
  ]
}

But I'm not sure how to instruct Vite to use this config on build.

typescript@4.8.4 vite@3.2.2


Solution

  • I found a way of specifying another tsconfig file through vite-plugin-dts. This is the plugin I'm already using to generate types during the build process.

    // vite.config.ts
    
    import vue from '@vitejs/plugin-vue'
    import { defineConfig } from 'vite'
    import dts from 'vite-plugin-dts'
    
    export default defineConfig({
      build: { ... },
      plugins: [
        vue(),
        dts({
          tsConfigFilePath: 'tsconfig.build.json',
        }),
      ],
    })
    

    Alternative solution

    The vite-plugin-dts options also allows to set excludes/includes that overrides tsconfig.json and makes a separate tsconfig.build.json redundant.

    // vite.config.ts
    
    import vue from '@vitejs/plugin-vue'
    import { defineConfig } from 'vite'
    import dts from 'vite-plugin-dts'
    
    export default defineConfig({
      build: { ... },
      plugins: [
        vue(),
        dts({
          exclude: [
            'node_modules',
            'cypress'
          ],
        }),
      ],
    })