Exclude test files from Compilation in TypeScript


Borislav Hadzhiev

Sat Mar 12 20222 min read


Photo by freestocks

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, which uses the excludes 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 like:

{ "scripts": { "build": "tsc --project tsconfig.build.json", } }
Now, whenever you run the tsc command the test files will not get compiled and 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.

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. The --project flag instructs TypeScript to compile the project based on the specified configuration file.

Use the search field on my Home Page to filter through my more than 1,000 articles.