2
Author: Dmitri Pavlutin
Translator: Frontend Xiaozhi
Source: dmitripavlutin
There are dreams, dry goods, WeChat search [Da Qian World] Pay attention to this Shuawanzhi who is still doing dishes in the early morning.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

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

However, it is often convenient to save the configuration of the application in a JSON file. Therefore, we may want to import the JSON file directly into the ES module.

For a long time, the commonjs module format supports importing JSON.

The good news is that a new proposal called the JSON module in the third phase proposes a way to import JSON into the ES module. Now, let's take a look at how the JSON module works.

1. Import config.json.

Suppose, we have a config.json file, the content is as follows:

{
  "name": "My Application",
  "version": "v1.2"
}

How to config.json into ES module?

For example, we create a simple web application to display the name and version of the application from a JSON configuration file.

If you try to import config.json directly, Node.js will throw 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);

When trying to run the application, node.js throws error TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json"

image.png

When Node.js uses the import statement, it expects JavaScript code by default. But thanks to the proposal of the JSON module, you can indicate the type of data you want to import: JSON .

Before fixing the application, let's take a look at what is included in the JSON module proposal.

2. JSON module proposal

The essence of the JSON module proposal is to allow the use of regular import statements to import JSON data in the ES module.

You can import JSON content by adding import assertions:

import jsonObject from "./file.json" assert { type: "json" };

assert {type: "json"} is an import assertion, indicating that the module should be parsed and imported as json.

jsonObject variable contains ordinary JavaScript objects created after file.json

The content of a JSON module is imported by default, and named imports are not available.

The JSON module can also be dynamically imported:

const { default: jsonObject } = await import('./file.json', {
  assert: {
    type: 'json'
  }
});

When a module is dynamically imported, including a JSON module, the default content is available default

In this case, the import assertion represents the JSON type. However, there is a more general proposal to import assertions (currently in phase 3), allowing the import of more data formats, such as CSS modules.

3. Enable JSON module

Now, we integrate the JSON module into the 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);

The main module now imports the config.json file and accesses its values config.name and config.version .

image.png

The JSON module works in Node.js version >=17.1 . You can also use the --experimental-json-modules flag to enable the Experimental JSON module

node --experimental-json-modules index.mjs

In the browser environment, the JSON module is available starting from Chrome 91.

4. Summary

By default, ES modules can only import JavaScript code.

Thanks to the proposal of the JSON module, you can directly import the JSON content into the ES module. Just use the import assertion after the import statement.

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

You can use the JSON module from Node.js 17.1, use the experimental flag --experimental-json-modules , and use it in Chrome 91 and above.


code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://dmitripavlutin.com/javascript-json-modules/

comminicate

If you have dreams and dry goods, search on for 161ccf6904ce2c [Moving to the World] Follow the brushing wisdom who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.


王大冶
68.1k 声望105k 粉丝