使用TypeScript 3项目引用时出现“找不到模块”错误

10

我正在尝试让 TypeScript 3 的项目引用 正常工作,但是在从被引用的项目中导入函数方面遇到了困难。

我有一个名为 ProjectA 的项目,它引用了 Shared。以下是文件结构:

ProjectA
|_ src
|     |_person.ts
|_ tsconfig.json
|
Shared
|_ src
      |_utils.ts
|_ tsconfig.json

这里是 utils.ts 文件:
export function guid() {
  return "a guid";
}

这是 Shared/tsconfig.json 文件的内容:
{
  "compilerOptions": {
    "composite": true,
    "declaration": true,

    "target": "es5",
    "outDir": "dist",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "noImplicitReturns": true,
    "noImplicitAny": true
  },
  "include": ["src/**/*"]
}

这里是ProjectA/tsconfig.json文件:

{
  "compilerOptions": {
    "composite": true,
    "declaration": true,

    "target": "es5",
    "outDir": "dist",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "noImplicitReturns": true,
    "noImplicitAny": true
  },
  "include": ["src/**/*"],
  "references": [{ "path": "../shared" }]
}

以下是有问题的文件 - person.ts

import { guid } from "../../Shared";

class Person {
  id: string;
  name: string;
  constructor() {
    this.id = guid();
  }
}

TS编译器报错:"无法找到模块 '../../Shared'"

enter image description here

当尝试导入guid函数时,我做错了什么?任何帮助都将不胜感激。
1个回答

8
你需要使用完整的相对路径来导入文件,就像如果该文件在同一项目中一样:
import { guid } from "../../Shared/src/utils";

我使用路径映射来使我的模块以更好的方式可访问:https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping。我知道这不是最初的问题,但有些人可能喜欢使用import * from 'my-module'而不是import * from '../../my-module',所以我想在这里提一下。 - siyb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接