VSCode 和 Typescript 5 模块解决方案“捆绑程序”

Joh*_*enz 18 typescript visual-studio-code

我正在尝试将 typescript 5.0.2 和 vscode 1.76.2 与 tsconfig 中的新 moduleResolution“bundler”设置一起使用。我正在使用 vite 构建一个前端,因此 typescript 仅用于使用--noEmit. 我可以单独获取 vscode 并tsc --noEmit使用不同的 tsconfigs,但无法让两者一起工作。

模块节点16

如果在 tsconfig.json 中,我有

{
  "module": "node16",
  "moduleResolution": "bundler"
 ...
}
Run Code Online (Sandbox Code Playgroud)

然后 Visual Studio Code 就可以完美运行,它可以对所有文件进行类型检查,一切都很棒。但是,运行tsc --noEmit出现错误

tsconfig.json:4:25 - error TS5095: Option 'bundler' can only be used when 'module' is set to 'es2015' or later.

4     "moduleResolution": "bundler",
                          ~~~~~~~~~


Found 1 error in tsconfig.json:4
Run Code Online (Sandbox Code Playgroud)

模块 es2020

从上面的 tsc 错误中,我尝试将 tsconfig.json 更改为

{
  "module": "es2020",
  "moduleResolution": "bundler"
 ...
}
Run Code Online (Sandbox Code Playgroud)

现在运行tsc --noEmit完美,它运行和类型检查一切都很完美。但现在vscode坏了。当我在 vscode 中打开 ts 文件时,vscode 无法解析任何引用。当我将鼠标悬停在 @mui/material 等导入上时,vscode 会给出错误

Cannot find module '@mui/material'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?
Run Code Online (Sandbox Code Playgroud)

两个独立的 tsconfig

现在,我只是做了两个单独的 tsconfig。tsconfig.json 有 "module": "nodenext" 以便 vscode 可以工作,然后我将 tsc 指向一个单独的 tsconfig.file。

是否有 tsconfig 的配置可以同时与 tsc 和 vscode 一起使用?

小智 12

这实际上只是 VSCode 版本问题。

我使用的是VSCode 1.76.2,也遇到了同样的问题。当我导入vite@vitejs/plugin-react时,我的vite.config.js文件出现错误。此外,当我尝试导入第三方库时,我在任何其他文件中都出现错误。在该 VSCode 版本中,我发现的唯一修复是将tsconfig.jsontsconfig.node.json中的从 更改为bundlernode

模块bundler解析是一个新功能,在Typescript 5.0上实现,我认为 VSCode 还没有 100% 准备好。

我刚刚在这里更新(现在我有VSCode 1.77.3),并且可以将tsconfig.jsontsconfig.node.json模块分辨率改回bundler。没有更多问题了!