【问题标题】:typescript 4.4.4: tsconfig paths not resolving as expectedtypescript 4.4.4:tsconfig 路径未按预期解析
【发布时间】:2021-12-08 16:13:46
【问题描述】:

我的 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 不理解“@”是什么,因此我收到“找不到模块”错误。我该如何解决这个问题?

【问题讨论】:

    标签: node.js typescript typescript2.0


    【解决方案1】:

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

    tl;博士

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

    【讨论】:

    • 我使用的是配置了 webpack 的 CRA,这就是它在那里工作的原因,但在这里我正在运行 nodejs,但它没有。你的回答很有道理。谢谢。
    猜你喜欢
    • 2019-01-28
    • 2020-05-06
    • 2019-03-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多