分享一个nodejs项目的tsconfig配置

197 阅读2分钟

抄作业

{
  "compilerOptions": {
    /* 基础配置 */
    "target": "ES2022",               // 使用现代 ES 标准(匹配 Node.js 18+)
    "module": "NodeNext",             // 使用 Node.js 的模块解析方式
    "moduleResolution": "NodeNext",   // 明确指定 Node 模块解析策略
    "outDir": "./dist",               // 编译输出目录
    "rootDir": "./src",               // 源码根目录
    
    /* 类型检查增强 */
    "strict": true,                   // 开启所有严格类型检查
    "noImplicitAny": true,            // 禁止隐式 any 类型
    "strictNullChecks": true,         // 严格的 null/undefined 检查
    "strictBindCallApply": true,      // 严格检查 bind/call/apply
    "strictFunctionTypes": true,      // 严格函数类型检查
    
    /* 模块处理 */
    "esModuleInterop": true,          // 改进 CommonJS/ESM 互操作性
    "resolveJsonModule": true,        // 允许导入 JSON 文件
    "allowSyntheticDefaultImports": true, // 允许 CJS 模块的默认导入
    
    /* 源码映射 */
    "sourceMap": true,                // 生成 sourcemap
    "inlineSources": true,            // 将源码嵌入 sourcemap
    
    /* 实验性特性 */
    "experimentalDecorators": true,   // 启用装饰器(如需使用装饰器)
    "emitDecoratorMetadata": true,    // 生成装饰器元数据
    
    /* 路径别名 */
    "baseUrl": ".",                   // 基准路径
    "paths": {
      "@/*": ["src/*"]                // 路径映射配置
    }
  },
  "include": ["src/**/*.ts"],         // 包含文件
  "exclude": [                       // 排除文件
    "node_modules",
    "dist",
    "**/*.spec.ts",
    "**/*.test.ts"
  ]
}

细节解析

  1. 目标环境配置

    "target": "ES2022",
    "module": "NodeNext"
    
    • 选择 ES2022 以支持最新 ES 特性(需 Node.js 18+)
    • NodeNext 模式确保与 Node.js 的 ESM/CJS 混合生态完美兼容
  2. 严格类型检查

    "strict": true,
    "noImplicitAny": true
    
    • 全家族严格模式开启,提升代码质量
    • 强制显式类型声明,避免 any 类型滥用
  3. 模块处理优化

    "esModuleInterop": true,
    "resolveJsonModule": true
    
    • 解决 CommonJS 模块的默认导入问题(如 import Koa from 'koa'
    • 支持直接导入 JSON 文件(适用于配置文件场景)
  4. 路径别名配置

    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
    
    • 实现类似 import router from '@/routes' 的简洁导入方式
    • 需配合 module-alias 等运行时库使用
  5. 源码映射配置

    "sourceMap": true,
    "inlineSources": true
    
    • 生成高质量的 sourcemap 文件
    • 生产环境建议通过构建流程分离 sourcemap
  6. Node.js 特性支持

    "moduleResolution": "NodeNext"
    
    • 确保正确解析 Node.js 的模块查找规则
    • 支持 package.jsonexports 字段解析