user16435030
user16435030

Reputation:

TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file:///path/to/data.json" needs an import assertion of type "json"

I'm trying to import JSON in nodejs.

// tsconfig.json

...
  "lib": ["es2022"],
  "target": "es2022",
  "module": "nodenext",
  "moduleResolution": "node",
...
  "resolveJsonModule": true,
...

// .swcrc.json

...
  "target": "es2022",
...
  "module": {
    "type": "nodenext",
...

When I then compile it and run "start": "NODE_ENV=production node --es-module-specifier-resolution=node --experimental-json-modules --no-warnings lib/index.js" I get TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file:///path/to/data.json" needs an import assertion of type "json".

I then add:

import data from './data.json' assert {type: 'json'}

console.log(data)

I then open up the compiled code and I can see:

import data from"./data.json";console.log(data);
//# sourceMappingURL=index.js.map

At this point I thought maybe it's SWC not compiling the assertation?

I then run tsc --emitDeclarationsOnly and I get Import assertions are not allowed on statements that transpile to commonjs 'require' calls. At this point I have no idea why on earth commonjs has anything to do with it, I'm not using commonjs anywhere am I?

Also I'm using node 18.

What am I doing wrong? I am simply trying to import that json.

Edit: Okay so the reason TS was breaking was because of missing "include": ["src/**/*.ts", "src/**/*.json", "types.d.ts"],. After adding that it now works. Unfortunately SWC is still giving the same error so I cannot run it.

Upvotes: 3

Views: 8739

Answers (1)

user16435030
user16435030

Reputation:

Finally figured it out. There's an experimental option in .swcrc.json that allows you to tell it to keep the assertations.

// .swcrc.json

...
"jsc": {
  "experimental": {
    "keepImportAssertions": true
  }
}

Upvotes: 2

Related Questions