How to import JSON into JavaScript module — JSON modules

Marian Čaikovski
3 min readJun 1, 2021

Lately it is possible without top level await for fetch.

Why to load a JSON as a module?

JSON modules are intended for the applications made up of JavaScript modules. JSON modules allow loading static or dynamically generated data during loading of JavaScript modules. With JSON modules ES modules got less inferior to AMD modules.

There might be many use cases for JSON modules, but I will describe how they simplify a task that I regularly face. In some web applications the start page layout or contents depend on some settings, for example the user privileges or preferences. Before rendering the start page, such applications have to load some client-specific initial data.

For the sake of simplicity, let’s imagine an application that requires the user name for laying out the start page. Once the start page with some base content is rendered, the application loads and renders more data. The entry point into the sample application is a simple main.js:

// main.js
import layout from './init/layoutUser.js';
import loadAndRenderData from './init/loadAndRenderData.js';
layout();
loadAndRenderData();

loadAndRenderData() is called after the user-specific start view has been laid out by…

--

--

Marian Čaikovski

Java, JavaScript and SQL developer. Interested in data collection and visualization.