15

I couldn't find any answers on importing JSON files with the new ES modules implementation, all the answers that I've found on StackOverflow are for code that's transpiled using Babel, I want to import my package.json file:

import pkg from '../package.json';

And I'm getting this error:

(node:7863) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/run_main.js:54
    internalBinding('errors').triggerUncaughtException(
                              ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /home/user/files/project/package.json imported from /home/user/files/project/version.js
    at Loader.resolve [as _resolve] (internal/modules/esm/default_resolve.js:126:13)
    at Loader.resolve (internal/modules/esm/loader.js:72:33)
    at Loader.getModuleJob (internal/modules/esm/loader.js:156:40)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
    at link (internal/modules/esm/module_job.js:41:36) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

I'm using the latest Node.js 13.6.0, am I only left with the option to read the file using the fs module?

Pierre
  • 12,468
  • 6
  • 44
  • 63
  • 1
    Does this answer your question? [How to import a json file in ecmascript 6?](https://stackoverflow.com/questions/34944099/how-to-import-a-json-file-in-ecmascript-6) – Justin Workman Jan 14 '20 at 17:37
  • Um, JSON isn't Javascript, so why would you think that it would? Just read the file and parse the contents. – Jared Smith Jan 14 '20 at 17:45
  • @JustinWorkman Actually no, I've checked all the answers and none of them worked for me, I wanted to check if there's a solution other than reading the file. – Pierre Jan 14 '20 at 17:57
  • @Pierre you have two options: read the file and parse the contents, or use a loader like webpack that deals with non-JS assets (not appropriate for a node project, obvs). Ecmascript modules are for, well, *Ecmascript*, JSON is completely different. – Jared Smith Jan 16 '20 at 12:34
  • https://stackoverflow.com/a/60206393/1653236 – CodeFinity Sep 24 '21 at 12:55

2 Answers2

28

I've found in the Node.js ES Modules docs that currently importing JSON is only supported in the CommonJS mode and the flag --experimental-json-modules is required for importing JSON files in ES modules.

Assuming an index.mjs with

import packageConfig from './package.json';

The --experimental-json-modules flag is needed for the module to work.

node index.mjs # fails
node --experimental-json-modules index.mjs # works
Pierre
  • 12,468
  • 6
  • 44
  • 63
  • 7
    That is *really terrible*, what a slap in the face to portability. Ah well, looks like you got your answer, +1. – Jared Smith Jan 16 '20 at 12:37
-11

You can import it as so:

import *  as config from '../config.json'
Carlos Franco
  • 58
  • 1
  • 1
  • 11