Exclude test files from Compilation in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
2 min

banner

# 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.

tsconfig.json
{ "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"] }
The code for this article is available on GitHub

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

tsconfig.build.json
{ "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.

shell
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.

package.json
{ "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.

tsconfig.build.json
{ "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.

package.json
{ "scripts": { "build": "tsc --project tsconfig.build.json", } }
The code for this article is available on GitHub

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 ยฉ 2024 Borislav Hadzhiev