Exclude test files from Compilation in TypeScript

Borislav Hadzhiev

Last updated: Jan 23, 2023
2 min


# Exclude test files from Compilation in TypeScript

To exclude test files from compilation, but still have them type checked, create a second configuration file, e.g. tsconfig.build.json that uses the exclude array to exclude your test files from compilation when running the tsc command.

Here is the main tsconfig.json file.

{ "compilerOptions": { "module": "commonjs", "target": "es6", "outDir": "./build" }, // ๐Ÿ‘‡๏ธ also include your test files in the `include` array // if they are outside of the `src` directory "include": ["src/**/*"], "exclude": ["node_modules"] }

And here is the tsconfig.build.json file that's located in the same directory as the tsconfig.json file.

{ "extends": "./tsconfig.json", // ๐Ÿ‘‡๏ธ this may vary depending on how you // name your test files "exclude": [ "src/**/*.spec.ts", "src/**/*.test.ts" ] }

Note that the tsconfig.build.json file extends from our tsconfig.json file.

The path assumes that the two configuration files are located in the same directory.

The file also excludes the test files from compilation, so they don't end up in your outDir (build in the example above).

Now you have to pass the tsconfig.build.json configuration file when using the tsc command.

tsc --project tsconfig.build.json

Your build command is most likely in your package.json file, so you can update it to look something similar to the following.

{ "scripts": { "build": "tsc --project tsconfig.build.json", } }
Now, whenever you run the tsc command, the test files won't get compiled and won't end up in your build directory but they will still be type checked.

The exclude array in the tsconfig.build.json file in the example assumes that you place your test files in the src directory of your project and name them *.spec.ts or *.test.ts.

{ "extends": "./tsconfig.json", // ๐Ÿ‘‡๏ธ this may vary depending on how you // name your test files "exclude": [ "src/**/*.spec.ts", "src/**/*.test.ts" ] }

If you have a different naming convention for your test files, make sure to tweak the excluded paths.

Make sure to update your build command to use the new tsconfig.build.json file.

{ "scripts": { "build": "tsc --project tsconfig.build.json", } }

The --project flag instructs TypeScript to compile the project based on the specified configuration file.

I've also written a detailed guide on how to exclude a folder from compilation.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev