3

I would like to import a JSON5 file into a Javascript object in the same way [one can import a JSON file](import config from '../config.json').

PrintScreen

Shows this message on hovering but it's clearly there

Cannot find module '../conf/config.json5' or its corresponding type declarations.ts(2307)

I have 2 side questions related to the main one above:

  1. Will I get intelisense for contents inside .json5, like regular json
  2. Does it even work like it works with require()? Do I have to use import() instead of regular import ?
Inigo
  • 12,186
  • 5
  • 41
  • 70
Zoro
  • 43
  • 5

2 Answers2

5

You will need the package to do so: json5.

There are one of two ways we can use this:

One: (target module system is CommonJS) require it

Following the README, we register json5:

import "json5/lib/register";

Then you can use require to import it:

const config = require("../config/config.json5");

Two: Reading the file and then using json5 to parse it:

import json5 from "json5";
import { readFile } from "fs/promises";

(async () => {
    const text = await fs.readFile("./path/to/config.json5"); // path to config.json5 from entry point

    const config = json5.parse(text);
})();

You can also use the provided CLI to convert json5 files to regular json that you can use.

kelsny
  • 23,009
  • 3
  • 19
  • 48
  • Ah thanks, I thought I couldn't use require when specified to use imports in tsconfig Also, I noticed I don't get intellisense with either of methods, any workaround on that? – Zoro Feb 19 '22 at 14:18
  • If you mean `config` isn't the correct structure (probably `any`), you will have to explicitly type it yourself. However `json5` should have library typings provided already. – kelsny Feb 19 '22 at 14:20
  • I tried for a while, doesn't look like I get autocomplete or any type checking on contents of that config. – Zoro Feb 19 '22 at 14:54
0

The creator updated the json5 wiki

Wiki

You need to create an extra file with .d.ts extension to support intellisense.

Zoro
  • 43
  • 5