在 TypeScript 中排除使用 tsconfig.json 中的模式
Exclude using a pattern in tsconfig.json in TypeScript
使用通配符来排除使用tsconfig.json
. 文件中的
exclude
数组tsconfig.json
支持通配符来制作 glob 模式。例如,星号*
匹配零个或多个不包括目录分隔符的字符。
{ "compilerOptions": { // ... your compiler options }, "include": ["src/**/*"], "exclude": [ "node_modules", "src/**/*.spec.ts", "src/**/*.test.ts", "src/some-directory" ] }
上面的示例使用
include选项指定要包含在代码库中的模式。
tsconfig.json
文件的目录进行解析。exclude数组包含解析数组时应跳过的文件名或模式include
。
该exclude
选项会更改该include
选项找到的内容,有效地从编译中过滤掉一些文件夹或文件。
如果您不想编译测试,但仍希望在测试文件中启用类型检查,请查看我的另一篇文章 –
从 TypeScript 的编译中排除测试文件。
include
和exclude
选项支持
glob 模式的通配符:
*
– 匹配零个或多个字符(不包括目录分隔符)?
– 匹配任何一个字符(不包括目录分隔符)**/
匹配嵌套到任何级别的任何目录
By default files with the following extensions are included: – .ts
, .tsx
,
.d.ts
.
If you’ve set allowJs
to true
in your tsconfig.json
options, then .js
and .jsx
files are also included by default.
The src/**/*.spec.ts
glob pattern matches all files that have a .spec.ts
extension in the src
directory.
{ "compilerOptions": { // ... your compiler options }, "include": ["src/**/*"], "exclude": [ "node_modules", "src/**/*.spec.ts", "src/**/*.test.ts", "src/some-directory" ] }
Regardless of where exactly in the src
directory the file with the .spec.ts
extension is located, it will be excluded.
src
directory in the include
option, so we are using the exclude
array to filter out some directories and files that we don’t want to compile.If you don’t explicitly add the exclude
array in your tsconfig.json
file, it
defaults to node_modules
, bower_components
and jspm_packages
.
Adding a pattern or files to your exclude
array does not prevent the files
from being included in the codebase, it changes what the include
setting
finds.
For example, if you have the src/some-directory
path in your exclude
array
and create a file under src/some-directory/my-file.ts
, it could still be
included in your project if you import any of its exports in a file that is
being type checked.
如果您将排除的文件添加到文件中的文件选项,
则它们也可能最终成为项目的一部分tsconfig.json
。
如果您不想编译测试,但仍希望在测试文件中启用类型检查,请查看我的另一篇文章 –
从 TypeScript 的编译中排除测试文件。