在TS文件中导入JS模块

时间:2020-02-27 14:27:18

标签: javascript typescript node-modules

在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
  }
}

1 个答案:

答案 0 :(得分:0)

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