ERR_IMPORT_ASSERTION_TYPE_MISSING for import of json file

Viewed 18506

This code was working fine.

I don't know if it's because I upgraded to Node 17 or what, but now I get

TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]:
  Module "file:///Users/xxxxx/code/projects/xxxxx/dist/server/data/countries.json" 
  needs an import assertion of type "json"

In my api.ts I have:

import countryTable from './data/countries.json';

Here's how I start api.ts which is used by server.ts:

NODE_ENV=production node --optimize_for_size --trace-warnings --experimental-json-modules --no-warnings server/server.js
2 Answers

For anyone having ESLint validation issues (due to assert not being supported yet), you can try loading the JSON from the filesystem synchronously:

const loadJSON = (path) => JSON.parse(fs.readFileSync(new URL(path, import.meta.url)));

const countries = loadJSON('./data/countries.json');

Reference: https://github.com/eslint/eslint/discussions/15305

Related