简体   繁体   中英

Typescript Import vs JavaScript import

/module/c.js, trying to export name and age.

export const name = 'string1';
export const age = 43;

b.ts, I'm trying to import name and age in this.ts file


import { name, age } from "./module/c";
console.log(name, age);

Compile will get error like this: "TS7016: Could not find a declaration file for module './module/c'."

I search and found a workaround: using // @ts-ignore, this can ignore grammar validation..

// @ts-ignore
import { name, age } from "./module/c";
console.log(name, age);

Question: This is a abnormal way for such kind of issue, is there any other ways to fix the issue? Btw, will be great if there's an example.. thx

Since your c.js is a JavaScript file, you should set "allowJs": true in your tsconfig.json file to allow importing from a .js file.

An example of a tsconfig.json file would be:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  }
}

src/b.ts

import { name, age } from "./module/c";
console.log(name, age);

src/module/c.js

export const name = 'string1';
export const age = 43;

Output of executing node dist/b :

string1 43

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-2024 STACKOOM.COM