【问题标题】:"Cannot find module" error when using TypeScript 3 Project References使用 TypeScript 3 项目参考时出现“找不到模块”错误
【发布时间】:2019-02-16 09:41:19
【问题描述】:

我正在尝试使 TypeScript 3 的项目引用正常工作,但难以从引用的项目中导入函数。

我有一个引用 SharedProjectA。这是文件结构:

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();
  }
}

“找不到模块 '../../Shared'”的 TS 编译器错误

尝试导入 guid 函数时我做错了什么?任何帮助将不胜感激

【问题讨论】:

    标签: typescript typescript3.0


    【解决方案1】:

    您需要使用要从中导入的文件的完整相对路径,就像文件在同一个项目中一样:

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

    【讨论】:

    • 我使用路径映射使我的模块以更好看的方式访问:typescriptlang.org/docs/handbook/…。我知道这不是最初的问题,但有些人可能喜欢使用 import * from 'my-module' 而不是 import * from '../../my-module' 所以我想在这里提一下.
    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 2018-02-01
    相关资源
    最近更新 更多