Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the ES modules implementation support importing JSON files?

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?

like image 831
Pierre Avatar asked Jan 14 '20 17:01

Pierre


People also ask

Do you have to import JSON?

x yes you can require your JSON just as you would require a js file.

What is import JSON in Python?

It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script.

What are JSON modules?

This module contains functions for working with JSON data. You can use it to process JSON that is embedded in other file formats. For example, you can query JSON that is stored as lines in a large text file by using json:parse-as-xml with the text:collection function.


Video Answer


1 Answers

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
like image 128
Pierre Avatar answered Oct 17 '22 07:10

Pierre