打字稿 4.4.4:tsconfig 路径未按预期解析

typescript 4.4.4: tsconfig paths not resolving as expected

我的tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "CommonJS",
    "lib": ["ESNext", "ESNext.AsyncIterable"],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@config": ["src/config"],
    }
  },
  "exclude": ["node_modules"],
  "include": ["./src/**/*.ts"]
}

我很确定 tsconfig 路径没有任何问题,因为我什至从 IDE 获得了路径自动完成功能。然而,当我的代码被编译时 (tsc --project tsconfig.json)

import { PRODUCTION } from '@config';

// or

import { PRODUCTION } from '@/config';

我关注了 javascript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _config_1 = require("@config");
console.log(_config_1.PRODUCTION);
//# sourceMappingURL=index.js.map

但 javascript 不明白“@”是什么,因此我收到“找不到模块”错误。我该如何解决这个问题?

在 TypeScript 的 GitHub 项目上查看此问题:Module path maps are not resolved in emitted code (#10866)

tl;博士

  • TypeScript 不会重写您的模块路径
  • paths 旨在帮助 TypeScript 理解打包器使用的路径别名
  • 您需要:
    • 使用打包器,例如webpack,并配置自己的路径映射
    • 使用构建时工具,例如 tspath,重写路径
    • 修改运行时模块解析器,类似module-alias