简体   繁体   中英

Importing JS module in TS file

In Visual Studio Code, when there are two .js module files A.js and B.js , importing module A inside module B allows us to use autocomplete on imported module. When importing module A into C.ts this autocomplete is not available and ofcourse message appears Could not find a declaration file for module <PATH_TO_A_MODULE> . I saw answers that suggest creating declaration files for module A, but I want to avoid this because VS Code already "knows" declarations since it is working when importing JS module into another JS module. Environment is nodejs.

Example:

// 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

Is there a way to allow importing JS modules into TS files without declaration files so that autocompleting and typing is working?

EDIT: (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
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM