typescript - 使用具有多个 tsconfig 的自定义导入路径时找不到模块

标签 typescript

我有一个包含多个 tsconfig.json 文件的项目。我想缩短所有导入,但由于某些原因,缩短的导入在特定情况下不起作用。

项目结构:

foo/
|  main.ts
|  tsconfig.json
projects/
|  bar/
|    index.ts
tsconfig.json

每当我想编译 foo/main.ts 时,我都会收到以下错误:Cannot find module @bar/shared

一些细节:

projects/bar/index.ts 文件只是导出一个普通类:export class Foo {}

foo/main.ts 尝试导入 Foo 类:

import {Foo} from '@bar/shared';

最后但同样重要的是 foo 中的 tsconfig.json:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true,
    "lib": ["es6", "dom"],
    "types": [
      "node"
    ],
    "outDir": "../dist/foo"
  }
}

和根 tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "@bar/shared": ["projects/bar"]
    }
  }
}

我的 IDE 完全满意 - 但我无法编译。

最佳答案

简答

在您的 foo/tsconfig.json 文件中,删除 baseUrl 条目,因为它错误地覆盖了根 baseUrl 条目 tsconfig.json 文件。

详情

baseUrl 值是从中解析非相对模块名称和 paths 映射条目的基本目录。因此,在解析@bar/shared映射入口时,模块解析策略是相对于./srcbaseUrl进行搜索。此外,由于 ./src 是相对路径,因此其完整路径基于其 /foo/tsconfig.json 文件的位置。因此,路径映射条目解析为 ./foo/src/projects/bar/

the module resolution docs 中提供了所有这些详细信息和更多信息.

--traceResolution

解决这些错误的一个很好的工具是使用 --traceResolution 选项进行构建。对于您的项目设置,从 foo/ 目录构建它包括以下输出:

Loading module as file / folder, candidate module location 'C:/dev/temp/foo/src/projects/bar', target file type 'TypeScript'.

运行时

TypeScript 路径映射允许路径映射,但不会重写这些路径。运行时(在您的情况下为 node)必须知道如何找到 @bar/shared。您还需要使用路径映射配置运行时。这是一个 node 包,可让您执行此操作:https://www.npmjs.com/package/module-alias

关于typescript - 使用具有多个 tsconfig 的自定义导入路径时找不到模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56565226/

相关文章:

webstorm 10.0.2 中的 typescript 1.5 beta,出现错误 : TS2304-Cannot find name 'DataView'

css - 更改单选按钮的大小

javascript - Angular js typescript 中的 Http promise

javascript - 无法读取 Angular 8 中未定义的属性 'push'

node.js - 使用 Typescript 向 expressjs 中的 req 对象添加属性

angular - 如何在 Ngrx 效果中参数化 Rx delay() 函数?

javascript - Angular 2 : check if routeName is the current one

css - 左 Angular 动画不起作用

javascript - 为什么在此 Vue 3 应用程序中带有参数的路由无法显示 404 View ?

angular - 失败 : Unexpected directive 'ContactDetailsComponent' imported by the module 'DynamicTestModule' . 请添加@NgModule 注解