jprichardson / node-jsonfile

Easily read/write JSON files.
MIT License
1.2k stars 321 forks source link

Breakage when running as ESM #153

Closed 500-internal-server-error closed 7 months ago

500-internal-server-error commented 7 months ago

Hello, I am trying to move away from old CJS in my project to the more modern ESM. Unfortunately, this module seems to break when running as ESM.

import * as jsonfile from "jsonfile"

const obj = jsonfile.readFileSync("./config.json");
console.log(JSON.stringify(obj, null, 4));

When I have "type": "commonjs" in my package.json, this file runs as expected. However, after switching to "type": "module" in my package.json, I get an error:

user@localhost:~/path/to/project $ tsx src/test.ts
file:///C:/path/to/project/test.ts:1
import*as jsonfile from"jsonfile";const obj=jsonfile.readFileSync("./config.json");console.log(JSON.stringify(obj,null,4));
                                                     ^
TypeError: jsonfile.readFileSync is not a function
    at file:///C:/path/to/project/test.ts:1:54
    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:120:12)

Node.js v21.7.1

This also happens when I tsc and node build/test.js.

I would love to be able to move to ESM, right now this module is the only thing stopping me (I tried to use raw JSON.parse and while that works, it would be nice if this module was usable with ESM).

Thanks in advance.

RyanZim commented 7 months ago

This module is still CommonJS, so it just has a single default export in ESM. You need to import it as import jsonfile from "jsonfile"