Why need exclude=["node_modules"] when I just have include=["src"] in my tsconfig.json?
Asked Answered
S

2

5

I want to compile just the "src" folder. hence i do include:["src"], and node_modules are found outside src only, then why do i need to exclude them like, exclude: ["node_modules"] as suggested by many sites?

e.g. they have also suggested that we include src and then exclude node_modules too - https://www.javatpoint.com/typescript-compilation-context

{  
    "compilerOptions": {  
        "module": "system",  
        "noImplicitAny": true,  
        "removeComments": true,  
        "preserveConstEnums": true,  
        "outFile": "../../built/local/tsc.js",  
        "sourceMap": true  
    },  
    "include": [  
        "src/**/*"  
    ],  
    "exclude": [  
        "node_modules",  
        "**/*.spec.ts"  
    ]  
}  

I shouldn't have to write any exclude in my tsconfig.json, right?

Selfgoverned answered 27/4, 2020 at 4:53 Comment(0)
J
4

You understood it incorrectly. Values in the include array represent folders/files that are going to be included in the program. exclude then specifies what folders/files must be excluded from the included folders/files.

In other words, if you write include: ['src'] and then exclude: ['*.spec.ts'], then you exclude every *.spec.ts file that was found under src folder.

You must exclude node_modules, even though the folder is outside the src folder. That's because those packages are imported (using import) inside the files (a.k.a modules) that are placed inside the included src folder. If you don't do that, TypeScript will check imported packages too and that's not something you want.

Since it is recommended to always exclude node_modules, TypeScript decided to add it as a default value. You can therefore omit the whole exclude specification if you only want to exclude node_modules.

Since you also want to exclude *.spec.ts files (not default), you need to specify it the way you did.

There are more folders that have been added to the array as default values ["node_modules", "bower_components", "jspm_packages"]

You can read more about this topic in the docs.

Jilly answered 29/7, 2021 at 16:36 Comment(0)
D
2

First, you don't have to specify the node_modules in the exclude option because TypeScript automatically excludes it by default.

If exclude is disabled, TypeScript will include these directories as excluding.

- node_modules
- bower_components
- jspm_packages
- the files <outDir> option specifies

The exclude option is only used as filtering of the include option. So you can specify it only when using the include option.

Check out more detail with a sample example here.

https://medium.com/javascript-in-plain-english/typescript-configuration-options-tsconfig-json-561d4a2ad4b

Delozier answered 10/12, 2020 at 1:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.