【问题标题】:Missing intellisense when importing .ts file in .js file在 .js 文件中导入 .ts 文件时缺少智能感知
【发布时间】:2022-08-02 20:57:23
【问题描述】:

我尝试使用tsx 运行由 JavaScript 和 Typescript 模块组成的 NodeJS 应用程序。 JavaScript 模块是 ESM,而不是 CommonJS。例如我有这些文件:

// provider.ts
export funcA(p: unknown): unknown {...}

// consumer.js
import * as provider from \"./provider.ts\"

provider.funcA(\"foo\");

它与 tsx 一起运行得很好。 VSCode 的智能感知在 TS 文件中运行良好,但在 JS 文件中却不行。当我悬停provider 它显示import provider 并且我没有完成任何事情。 这是我的tsconfig.json

{
  \"compilerOptions\": {
    \"module\": \"NodeNext\",
    \"target\": \"ESNext\",
    \"allowJs\": true,
    \"strict\": true,
  },
  \"include\": [
    <the directory containing both JS and TS files>
  ],
}

如何让 Intellisense 在 VSCode 中用于 JS 文件中的 TS 导入?

  • 你必须让它把 ts 编译成 js - javascript 就是不能加载 ts 文件
  • 就像我说的,我可以毫无问题地使用 tsx 运行我的代码。我的问题只是关于 VSCode 中的智能感知。 VSCode 嵌入了 TypeScript 编译器,因此它应该能够理解 JS 和 TS 并提供类型信息。

标签: javascript typescript visual-studio-code es6-modules tsx


【解决方案1】:

我找到了解决方案。当我导入 .ts 模块时,TypeScript 似乎无法理解。

我不得不删除导入的 .ts 部分。我必须将"moduleResolution": "Node" 添加到我的tsconfig.json 以消除解决错误。

我的 eslint 配置也遇到了一些问题。我安装了包@typescript-eslint/parsereslint-import-resolver-typescript 并将其添加到我的.eslintrc.json

"extends": [
  ...
  "plugin:import/typescript"
],
...
"settings": {
  "node": {
    "tryExtensions": [".js", ".node", ".ts"]
  }
}

现在它起作用了。我在我的 JS 文件中获得了完整的 Intellisense。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-09
    • 2018-04-14
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    相关资源
    最近更新 更多