Categories
JavaScript npm modules

Import JSON in Node in ESM Modules

Node 16.15 added support for importing JSON modules using the new assert { type: 'json' } syntax.

This is great news if you develop npm modules that need to be consumed both client and server side (or even just server side).

There’s a catch though… As of this writing it is a bit tricky to get working in Jest, and RollupJS just flat-out doesn’t support it (and the import assertions plugin also doesn’t work consistently).

Stefan Judis has a great post detailing importing JSON in JavaScript. The gist of it is that across the board in Node 16.15+ and in the browser, you should be able to do the following:

// An import assertion in a static import
import someData from `./someData.json` assert { type: `json` };

// An import assertion in a dynamic import
const { default: someData } = await import("./someData.json", {
  assert: {
    type: "json",
  },
});

But… Things don’t always work as they “should”. Which is why I made the test-json-import module and published it to npm. It is a minimal test case you can use to troubleshoot json imports in projects when you need to rule other things out (when making your _own_ minimal test case).

I’d love to hear about any uses you might put this to. Good luck!

Leave a Reply

Your email address will not be published.