阿里云主机折上折
  • 微信号
Current Site:Index > Detailed explanation of compilation configuration

Detailed explanation of compilation configuration

Author:Chuan Chen 阅读数:2748人阅读 分类: TypeScript

Compilation Configuration Details

TypeScript's compilation configuration is primarily implemented through the tsconfig.json file, which defines how the compiler converts TypeScript code into JavaScript. Understanding these configuration options is crucial for project building and code optimization.

Basic Structure of tsconfig.json

The tsconfig.json file is typically located in the project root directory and has the following basic structure:

{
  "compilerOptions": {
    // Compiler options
  },
  "include": [
    // Included files
  ],
  "exclude": [
    // Excluded files
  ]
}

Core Compiler Options

target and module

target specifies the JavaScript version to compile to, and module defines the module system:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS"
  }
}

Common target values:

  • ES3/ES5/ES6(ES2015)/ES2020
  • ESNext (latest features)

Common module values:

  • CommonJS (Node.js)
  • ES2015/ES2020 (modern browsers)
  • UMD/AMD (compatible with browsers and Node.js)

Strict Series Options

Strict type-checking-related configurations:

{
  "compilerOptions": {
    "strict": true,  // Enable all strict checks
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true
  }
}

Path and Module Resolution

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@components/*": ["src/components/*"],
      "@utils/*": ["src/utils/*"]
    },
    "moduleResolution": "node"
  }
}

Advanced Compilation Configuration

Type-Checking Related

{
  "compilerOptions": {
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  }
}

Source Maps

{
  "compilerOptions": {
    "sourceMap": true,
    "inlineSources": true,
    "declaration": true,
    "declarationMap": true
  }
}

Experimental Features

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "useDefineForClassFields": true
  }
}

File Inclusion and Exclusion

{
  "include": [
    "src/**/*",
    "tests/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

Project References

Large projects can use project references:

{
  "references": [
    { "path": "../core" },
    { "path": "../utils" }
  ]
}

Custom Transformers

Using custom transformers programmatically:

import * as ts from 'typescript';

function createTransformer(): ts.TransformerFactory<ts.SourceFile> {
  return context => {
    return sourceFile => {
      // Transformation logic
      return sourceFile;
    };
  };
}

const program = ts.createProgram([...], {
  transformers: {
    before: [createTransformer()]
  }
});

Multi-Environment Configuration

Different configurations for different environments:

// tsconfig.base.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true
  }
}

// tsconfig.node.json
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "module": "CommonJS"
  }
}

// tsconfig.web.json
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "lib": ["DOM", "ES2020"]
  }
}

Performance Optimization Options

{
  "compilerOptions": {
    "incremental": true,
    "tsBuildInfoFile": "./build/.tsbuildinfo",
    "composite": true
  }
}

Compiler Plugins

Extending compiler functionality with plugins:

{
  "compilerOptions": {
    "plugins": [
      { "transform": "ts-transformer-keys/transformer" },
      { "transform": "ts-nameof", "type": "raw" }
    ]
  }
}

Common Configuration Examples

Node.js Project Configuration

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Browser Project Configuration

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "jsx": "react-jsx",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    },
    "allowJs": true,
    "noEmit": true
  }
}

Compiler API Integration

Using the TypeScript compiler programmatically:

import * as ts from 'typescript';

const program = ts.createProgram(['file.ts'], {
  target: ts.ScriptTarget.ES5,
  module: ts.ModuleKind.CommonJS
});

const emitResult = program.emit();

const allDiagnostics = ts
  .getPreEmitDiagnostics(program)
  .concat(emitResult.diagnostics);

allDiagnostics.forEach(diagnostic => {
  if (diagnostic.file) {
    const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(
      diagnostic.start!
    );
    const message = ts.flattenDiagnosticMessageText(
      diagnostic.messageText,
      '\n'
    );
    console.log(
      `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`
    );
  } else {
    console.log(
      ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
    );
  }
});

Configuration Debugging

Use --showConfig to view the final configuration:

tsc --showConfig

Configuration Inheritance and Overrides

// tsconfig.base.json
{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true
  }
}

// tsconfig.extend.json
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "noImplicitAny": false  // Override base configuration
  }
}

Language Service Configuration

Configurations affecting editor experience:

{
  "compilerOptions": {
    "jsx": "preserve",
    "jsxFactory": "h",
    "jsxFragmentFactory": "Fragment"
  }
}

Output Control

{
  "compilerOptions": {
    "listFiles": true,
    "listEmittedFiles": true,
    "traceResolution": true,
    "diagnostics": true
  }
}

Multi-threaded Compilation

{
  "compilerOptions": {
    "incremental": true,
    "composite": true
  }
}

Custom Type Definitions

{
  "compilerOptions": {
    "typeRoots": ["./typings", "./node_modules/@types"],
    "types": ["node", "lodash"]
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:项目结构组织

下一篇:代码分割与优化

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.