【TypeScript】入门之tsconfig.json

2,093 阅读1分钟

概述

如果一个目录下存在一个tsconfig.json文件,那么意味着这个目录是TypeScript的根目录。

tsconfig.json文件中指定了用来编译这个项目的根文件和编译选项。一个项目可以通过以下方式之一来编译:

使用tsconfig.json

  • 不带任何输入文件的情况下调用tsc,编译器会从当前目录开始去查找tsconfig.json文件,逐级向上搜索父目录。
  • 不带任何输入文件的情况下调用tsc,且使用命令行参数--project(或-p)指定一个包含tsconfig.json文件的目录。

当命令行上指定了输入文件时,tsconfig.json文件会被忽略

示例

tsconfig.json示例文件:

  • 使用“files”属性

    {
        "compilerOptions": {
            "module": "commonjs",
            "noImplicitAny": true,
            "removeComments": true,
            "preserveConstEnums": true,
            "sourceMap": true
        },
        "files": [
            "core.ts",
            "sys.ts",
            "types.ts",
            "scanner.ts",
            "parser.ts",
            "utilities.ts",
            "binder.ts",
            "checker.ts",
            "emitter.ts",
            "program.ts",
            "commandLineParser.ts",
            "tsc.ts",
            "diagnosticInformationMap.generated.ts"
        ]
    }
  • 使用““include”和”exclude“属性

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

细节

"compilerOptions"可以被忽略,这时编译器会使用默认值。

"files"指定了一个包含相对或绝对文件路径的列表。"include"和"exclude"属性指定一个文件glob匹配模式列表,支持的glob通配符有:

  • * 匹配0或者多个字符(不包括目录分隔符)
  • ?匹配一个任意字符(不包括目录分隔符)
  • **/递归匹配任意子目录

如果一个glob模式里的某部分只包含*或者.*,那么仅有支持的文件扩展名类型被包含在内。

如果"files"和"include"都没有被指定,编译器默认包含当前目录和子目录下所有的TypeScript文件(.ts,.d.ts,.tsx)