This article is translated

JSON Modules in JavaScript

Originally by Dmitri Pavlutin

The original address: dmitripavlutin.com/javascript-…

The ECMAScript module system (import and export keywords) can only import JavaScript code by default.

Storing the application configuration in a JSON file is a great convenience, so you may want to import the JSON file directly into the ES Module.

The CommonJS module has supported JSON import for a long time.

Fortunately, a new proposal called JSON Modules has made it to stage 3, which is a way to import JSON in the ES Module. Let’s take a look at how JSON modules work.

1. Import config. Json

We’ll start with a JSON file, config. JSON, which contains some configuration items for the application: the name of the application and the current version.

{
  "name": "My Application"."version": "v1.2"
}
Copy the code

How do I import config.json into ES Module?

For example, we will create a simple Web application that will render the application name and version through a JSON configuration file.

We try to import config.json directly, and Node.js throws an error:

import http from 'http';
import config from './config.json';
http
  .createServer((req, res) = > {
    res.write(`App name: ${config.name}\n`);
    res.write(`App version: ${config.version}`);
    res.end();
  })
  .listen(8080);
Copy the code

Node.js raises TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.json” when starting the application.

When you use import statements in Node.js, you expect to import JavaScript code by default. But thanks to the JSON Modules proposal, we can specify JSON as the import data type.

Before fixing the application code, let’s take a quick look at what the JSON Modules proposal is.

2. JSON Modules proposal

The essence of the JSON Modules proposal is to allow JSON data to be imported in the ES Module using regular import statements.

We can import JSON content by adding import assertions:

import jsonContent from "./file.json" assert { type: "json" };
Copy the code

Assert {type: “json”} is an Import assertion that specifies the format in which the module should be parsed and imported as JSON.

The jsonContent variable stores the pure JavaScript objects created after parsing the file.json file.

The JSON Module import must be the default import. You cannot use named imports.

JSON Modules can also be dynamically imported:

const jsonContent = await import('./file.json', {
  assert: {
    type: 'json'}});Copy the code

In both of our examples, the import assertions specify the JSON type. But there is a more general assertion, import assertions (currently on Stage 3), that allows you to import more data formats, such as CSS modules.

3. Enable JSON modules

Now let’s integrate the JSON Module into our Web application:

import http from 'http';
import config from './config.json' assert { type: "json" };
http
  .createServer((req, res) = > {
    res.write(`App name: ${config.name}\n`);
    res.write(`App version: ${config.version}`);
    res.end();
  })
  .listen(8080);
Copy the code

The main module can now import config.json and has access to config.name and config.version.

JSON modules require node. js version 17.1 or later to work. Experimental JSON modules can also be enabled by carrying the –experimental-json-modules flag:

node --experimental-json-modules index.mjs
Copy the code

For browser environments, starting with Chrome 91, you can use JSON modules.

4. To summarize

By default, ES Module can only import JavaScript code.

Thanks to the JSON Modules proposal, we can import JSON content directly into the ES Module. Simply add the import assertion after the import statement:

import jsonContent from "./file.json" assert { type: "json" };
Copy the code

JSON modules can be used on Node.js versions 17.1 and up, or in browsers with experimental-json-modules or Chrome 91 and up.