【问题标题】:Importing JS module in TS file在 TS 文件中导入 JS 模块
【发布时间】:2020-06-11 14:18:26
【问题描述】:

在 Visual Studio Code 中,当有两个 .js 模块文件 A.js and B.js 时,在模块 B 中导入模块 A 允许我们对导入的模块使用自动完成功能。将模块 A 导入 C.ts 时,此自动完成功能不可用,并且当然会出现消息 Could not find a declaration file for module <PATH_TO_A_MODULE>。我看到了建议为模块 A 创建声明文件的答案,但我想避免这种情况,因为 VS Code 已经“知道”声明,因为它在将 JS 模块导入另一个 JS 模块时正在工作。环境是nodejs。

例子:

// A.js
export const some_variable = 1

// B.js
import * as A from 'A.js'
A.some_variable --> autosugestion and complete works

// C.ts
import * as A from 'A.js' --> this shows warning and autocomplete not available on A.
A.some_variable --> does not throw error but autocomplete is not working

有没有办法允许在没有声明文件的情况下将 JS 模块导入 TS 文件,以便自动完成和键入工作?

编辑:(tsconfig.json)

{
  "compilerOptions": {
    "baseUrl": ".",
    "esModuleInterop": true,
    "lib": ["es2015"],
    "module": "commonjs",
    "noImplicitAny": false,
    "outDir": ".build",
    "paths": {
      "*": ["node_modules/*"]
    },
    "preserveConstEnums": true,
    "resolveJsonModule": true,
    "rootDir": "",
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "es6",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "noImplicitUseStrict": true,
    "checkJs": true,
    "allowSyntheticDefaultImports": true,
    "declaration": true,
    "allowJs": true
  }
}

【问题讨论】:

  • 你的 tsconfig.json 是什么样的?您是否设置了“allowJs”标志?
  • 我刚刚添加了 tsconfig.json。我尝试添加allowJS,但问题仍然存在。代码运行良好,编译没有错误。

标签: javascript typescript node-modules


【解决方案1】:

您不能这样做,您需要为此添加类型以在 TypeScript 中导入 js 模块,请阅读:https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html

【讨论】:

  • 我已经阅读了它并且我知道声明文件是如何工作的,这对我来说很奇怪,当将 .js 模块导入另一个 .js 模块时,声明在没有声明文件但将 .js 模块导入到.ts 文件在 VS Code 中禁用自动完成和 IntelliSense
  • 那是因为你的 tsconfig 文件,你应该更新它,然后它也会导入 js 文件。
  • 你指的是哪个设置?
  • {allowjs:true} 在您的 tsconfig 中。
  • { "compilerOptions": { "target": "es5", "module": "es6" } } 试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
相关资源
最近更新 更多