typescript 4.4.4:tsconfig 路径未按预期解析

git*_*lot 10 node.js typescript typescript2.0

我的 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"]
}

Run Code Online (Sandbox Code Playgroud)

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

import { PRODUCTION } from '@config';

// or

import { PRODUCTION } from '@/config';
Run Code Online (Sandbox Code Playgroud)

我得到以下 javascript

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

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

Win*_*ing 20

请参阅 TypeScript 的 GitHub 项目上的此问题:发出的代码中未解析模块路径映射 (#10866)

太长了;博士


Vic*_*tor 14

我整整两天都被这个问题困扰,试图找到有效的方法。@Wing 的答案是正确的,如果您使用 plain而不使用其他工具,那么 Node 将不知道导入中的tsc含义(或您的别名是什么)。@/

\n

我尝试了几种不同的方法,并找到了一种不需要配置的方法。

\n

什么有效

\n

在我的旅程结束时,我遇到了一个仍在积极维护的软件包:tsc-alias。我唯一需要做的就是在构建脚本中添加 && tsc-alias -p tsconfig.json到我的命令中,然后 voil\xc3\xa0,它就可以工作了。tsc所以你的完整命令将类似于tsc -p tsconfig.json && tsc-alias -p tsconfig.json.

\n

我尝试过的方法不起作用

\n
    \n
  • 我尝试了“模块别名”,但无法让它工作。
  • \n
  • 我按照 @AlexMorley-Finch 的建议尝试了“tsconfig-paths”,但也没有运气。该包似乎正在寻找模块,但似乎存在一个错误,导致模块的路径无法正确映射(存在一个未解决的问题)。
  • \n
  • 然后我就遇到了tscpaths。该包要求您显式指定您的项目、src 目录和 out 目录。在弄清楚我的 outdir 需要代替 后,我让它开始./build/src工作./build。这里需要注意的是:自 2019 年 5 月撰写本文以来,此软件包尚未被触及。
  • \n
\n