Last updated: Feb 28, 2024
Reading timeยท2 min
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.
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", } }
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.