Happylab Logo
Published on

Day04: Understanding tsconfig.json Settings

Authors

Day04: Understanding tsconfig.json Settings


What is tsconfig.json?

It is a file for TypeScript compilation settings.

How to Generate tsconfig.json

As mentioned in the previous article, you can generate it by running the following command in the directory:

tsc --init

This will create the tsconfig.json file.

Default tsconfig.json

When we first get the tsconfig file, the default settings include:

{
  "compilerOptions": {
    "target": "es5", // Specify the JS version to compile to
    "module": "commonjs", // Specify the type of module to generate
    "strict": true, // Enable all strict type-checking options
    "esModuleInterop": true, // Compatibility for module imports
    "skipLibCheck": true, // Skip checking imported library files
    "forceConsistentCasingInFileNames": true // Ensure consistent casing in file names
  }
}

Other tsconfig.json Settings

In addition to the default compilerOptions, there are also:

  • compileOnSave: Set the compileOnSave property at the top level to allow the IDE to regenerate compiled files based on tsconfig.json when saving files.

  • compilerOptions: All compilation settings are written in compilerOptions. The default settings we obtained initially are in compilerOptions.

  • include: Specify the files or directories that need to be compiled.

  • exclude: Specify the files or folders that the compiler should exclude. By default, it excludes the node_modules folder.

    • Common wildcards for include and exclude include:
    • * - Matches zero or more characters (excluding separators)
    • ? - Matches a single character (excluding separators)
    • **/ - Matches all subfolders
  • extends: Import other configuration files and inherit settings. By default, it includes all TypeScript files in the current directory and subdirectories.

  • files: The value of files is a list of relative or absolute file paths that need to be compiled. By default, it includes all TypeScript files in the current directory and subdirectories. If files is specified, only the specified files will be compiled.

  • references: Specify the projects to reference. Sometimes, for convenience, front-end and back-end Node projects are developed in the same directory, relying on the same configuration file and common files.

  • typeAcquisition: Set automatic inclusion of library-related definition files. It includes three sub-properties:

    • enable: Boolean type, whether to enable automatic inclusion of library type definition files (.d.ts), default is false;
    • include: Array type, names of libraries to automatically include, e.g., ["jquery", "lodash"];
    • exclude: Array type, names of libraries to exclude.

Overall Example

{
  "compileOnSave": false, // Regenerate compiled files based on tsconfig.json when saving
  "compilerOptions": {
    /* Basic Options */
    "target": "es5", // Specify the JS version to compile to: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
    "module": "commonjs", // Specify the type of module to generate: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
    "lib": [], // Specific library files to include in compilation
    "allowJs": true, // Allow compilation of JavaScript files
    "checkJs": true, // Report errors in JavaScript files
    "jsx": "preserve", // Specify the generation of JSX code: 'preserve', 'react-native', or 'react'
    "declaration": true, // Generate corresponding '.d.ts' files
    "declarationMap": true, // Generate source maps for declaration files
    "sourceMap": true, // Generate corresponding '.map' files
    "outFile": "./", // Merge output files into a single file
    "outDir": "./", // Specify output directory
    "rootDir": "./", // The location where files should be placed
    "composite": true, // Whether to compile and build referenced projects
    "tsBuildInfoFile": "./", // Specify the file to store incremental compilation information, default is tsconfig.tsbuildinfo
    "removeComments": true, // Remove all comments after compilation
    "noEmit": true, // Do not produce output files
    "importHelpers": true, // Import helper functions from tslib
    "isolatedModules": true, // Treat each file as a separate module (similar to 'ts.transpileModule').

    /* Strict Type Checking Options */
    "strict": true, // Enable all strict type-checking options
    "noImplicitAny": true, // Report errors on expressions and declarations with an implicit 'any' type
    "strictNullChecks": true, // Enable strict null checks
    "strictFunctionTypes": true, // Enable checking of function types
    "strictBindCallApply": true, // Enable stricter type checking for bind, call, apply
    "strictPropertyInitialization": true, // Enable checks for class instance property assignments
    "noImplicitThis": true, // Generate an error when the value of 'this' expression is of type 'any'
    "alwaysStrict": true, // Check each module in strict mode and add 'use strict' to each file

    /* Additional Checks */
    "noUnusedLocals": true, // Throw an error when there are unused variables
    "noUnusedParameters": true, // Throw an error when there are unused parameters
    "noImplicitReturns": true, // Throw an error when not all code paths in a function return a value
    "noFallthroughCasesInSwitch": true, // Report fallthrough errors in switch statements
    "noUncheckedIndexedAccess": true, // Check if index signature properties are undefined

    /* Module Options */
    "moduleResolution": "node", // Choose module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)
    "baseUrl": "./", // Base directory for resolving non-relative module names
    "paths": {}, // List of path mappings for module names based on baseUrl
    "rootDirs": [], // List of root folders whose combined content represents the structure of the project at runtime
    "typeRoots": [], // List of files containing type declarations
    "types": [], // List of type declaration file names to include
    "allowSyntheticDefaultImports": true, // Allow default imports from modules without a default export.

    /* Source Map Options */
    "sourceRoot": "./", // Specify where the debugger should find TypeScript files instead of source files
    "mapRoot": "./", // Specify where the debugger should find map files instead of generated files
    "inlineSourceMap": true, // Generate a single soucemaps file instead of generating sourcemaps in different files
    "inlineSources": true, // Generate code and sourcemaps into a single file, requires both --inlineSourceMap or --sourceMap to be set

    /* Other Options */
    "experimentalDecorators": true, // Enable decorators
    "emitDecoratorMetadata": true, // Support for providing metadata for decorators

    /* Advanced Options */
    "skipLibCheck": true, // Skip checking imported library files
    "forceConsistentCasingInFileNames": true // Ensure consistent casing in file names
  },
  "files": [
    "hello.ts" // If files are specified, only the specified hello.ts file will be compiled.
  ],
  "exclude": [
    // Specify files or folders that the compiler should exclude
    "node_modules"
  ],
  "extends": "./tsconfig.base.json", // Extract basic configuration into tsconfig.base.json and import it

  "references": [
    // Specify paths to dependent projects
    { "path": "./common" }
  ],
  "typeAcquisition": {
    // Automatically include library-related definition files (.d.ts).
    "enable": false,
    "exclude": ["jquery"],
    "include": ["jest"]
  }
}

There may be a few settings missing in compilerOptions, but I don't fully understand their purposes yet. I will note down the settings that I use later.

Do you remember day02? I wrote my first TS using type annotation to specify types. In the next article, I will introduce the three methods for specifying types!


References

https://ithelp.ithome.com.tw/articles/10216636 https://segmentfault.com/a/1190000022809326 https://jkchao.github.io/typescript-book-chinese/project/compilationContext.html#tsconfig-json