3
votes

I am new in typescript and I have 2 questions.

a. I want to import a simple JSON file in my typescript (main.ts) using the following code in visual studio code (3.6.2) editor:

import test from "./test.json";
console.log(test.name);

I also tried with import * as test from "./test.json";

While the JSON file (test.json) is the following:

{"name": "testing",
"age":25}

However, when I am typing "test.", typescript is giving the options for "name", "age" as the properties.

And the tsconfig.json file is following:

{
  "compilerOptions": {
    "target": "es5", 
    "module": "commonjs",                     
    "strict": true, 
    "moduleResolution": "node",               
    "resolveJsonModule": true,
    "esModuleInterop": true
  }
}

This code is throwing the following error:

Cannot find module './test.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

Since the type definition is for old versions, I haven't used that. My typescript version is 3.6.3. The above mentioned 3 files are inside the same folder.

   -testfolder
     - main.ts
     - tsconfig.json
     - test.json

Though there are some other questions similar to this, but I couldn't find the problem in my code! I have also tested that with submile text 3 but it's also giving the same error!

b. If I want to parse a json data from a file where the file extension is different (not .json), how should I do that?

Thank you in advance for your time.

4
Is your json file at the same folder-level as main.ts? If it's not - import path should be relative to main.tsmayakwd
Yes, all the files are in the same folder.Nihar
Then if you using VS Code - just restart it, should help.mayakwd
Tried that, I restarted my pc too, but didn't help! :(Nihar

4 Answers

2
votes

try using a module. Review this documentation https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html

// index.ts

import file from "./file.json";

console.log(file);
console.log(file.name);

// json.dt.ts

declare module "*.json" {
  const file: any;
  export default file;
}
1
votes

Nihar,

I was able to reproduce the problem you mention. I was also able to resolve the problem using the following tsconfig.json:

{
"compilerOptions": {
  /* Basic Options */
  "target": "es5",
  "module": "commonjs",
  "strict": true,
  "esModuleInterop": true,
  "resolveJsonModule": true
}, 
"files": ["main.ts"]

}

Of course, the added "files" section assumes your main file is named "main.ts". Frankly I'm not sure why this works and your original does not, but when I use a tsconfig.json file, I try to put everything typescript needs to know in that one place.

0
votes

Given that you use VSCode and all the files are in the same directory and VSCode is opened from that directory directly, then your tsconfig works perfectly (for TS 3.6 at least).

0
votes

You can try to launch your app with this command

npm run serve --resolveJsonModule

your mistake may disappear