typescript - 如何让 VS Code 识别 mono-repo 包之间的 typescript 声明?

标签 typescript visual-studio-code yarnpkg parceljs

我有一个配置有独立库包(仅限 TS)和另一个 Web UI 包(TS + React)的单库项目。

我正在从消费者(Web UI)包中导入已编译的库包。为此,我使用 yarn 链接包和 parcel 以生成库包的分发文件。

包裹自动生成 d.ts库包中的文件 dist文件夹。

我将 VS Code 用作 IDE,当我打开导入库的消费者包文件并使用它时,VS Code 无法识别库包的 d.ts 中声明的类型文件。

这是包的结构:

rootPackage
|- library
|- web-ui

library包,我有一个 types.ts文件和 index.ts文件。只有一种类型被导出:

export type ParamType = "a" | "b" | "c";

我正在使用 parcel watch在这个包上自动刷新 dist发生更改时的文件。

包裹正在生成 main.d.ts文件就好了,这个文件正被 package.json 引用的 types属性。

当我尝试使用这个 ParamTypeweb-ui 输入包的代码,我在类型中突出显示了以下 IDE 错误:

Cannot find name 'ParamType'.ts(2304)

当我在 web-ui 中运行包裹时包,它编译得很好,浏览器加载没有问题/警告。

我认为这是一个专门与 VS Code 相关的问题,我不确定如何解决它。


编辑 1

我创建了一个 public repository on GitHub来证明这个问题。 如果您知道如何修复它,请随时创建拉取请求,这将非常有帮助。

最佳答案

从您的 example repo 开始,您的 library 包的根目录如下所示:

/shared/lib/src/index.ts

import { ParamType } from "./types";

const Library = {
  typedParamMethod(param: ParamType) {
    console.log(param);
  },
};

export default Library;

你在 library 包中使用 web-ui 包的方式是这样的:

/ui/web/src/App.tsx

import React from 'react';
import Library from 'library';

function App() {
  React.useEffect(() => {
    const typedParam: ParamType = 'b'; // VSCode and tsc throw the error "Cannot find name 'ParamType'." 
    Library.typedParamMethod(typedParam);
  }, []);

  return (
    <div className="web-ui">Web UI</div>
  );
}

export default App;

问题是您既没有将 ParamTypelibrary 包导出到根目录,也没有将其导入 web-ui 包。现代 JavaScript 和 Typescript 模块彼此隔离 - import { ParamType } from "./types" 包根目录中的 library 行使 ParamType 可用在该文件中,但它不会影响(或污染)发生的事情的全局命名空间从 library 包中导入其他内容(例如默认导出)。

要解决此问题,请将此行添加到 library 包根目录(例如 /shared/lib/src/index.ts ):

export { ParamType } from "./types.ts";

然后从你的 web-ui 包中修改导入(在 /ui/web/src/App.tsx 中:

import Library, { ParamType } from 'library';

(问题和解决方案与 VSCode 无关 - 任何尝试对 web-ui 包进行类型检查的内容都会发出相同的错误,但没有这些更改)

关于typescript - 如何让 VS Code 识别 mono-repo 包之间的 typescript 声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70103082/

相关文章:

javascript - 在新的 React 图表中使用从 Highcharts 编辑器导出的数据

在 Chrome 中调试从 TypeScript 生成的动态加载的 Javascript

visual-studio-code - 如何调试Visual Studio Code扩展?

java - Visual Studio Code 运行时检索 UnsupportedClassVersion 错误

node.js - IntelliJ Ultimate Yarn 需要 nodejs 4 或更高版本

yarnpkg - 发布包时出错 - "name"对于新包无效

arrays - 如何仅使用一个函数按属性对对象数组进行排序?

javascript - 将 [Sequelize.Op.in] 用于 json 对象数组

visual-studio-code - 为什么 Jupyter notebook 在 VS Code 中显示为 JSON 文件?

git - yarn v2 gitignore