ยท hands on

Loading JSON Files Dynamically in TypeScript

Learn how to dynamically import JSON files in TypeScript using import attributes and dynamic imports. Also, discover how to use `require` in ECMAScript modules with Node.js.

Using Import Attributes, the evolution of Import Assertions, you can dynamically import JSON files at runtime in a TypeScript codebase. This process involves using import attributes in conjunction with a dynamic import, as shown in the following example:

async function loadJSON(filename: string) {
  const json = await import(filename, {
    with: { type: 'json' },
  });
 
  return json.default;
}

The await import(), known as dynamic import, is a function that returns a promise and initiates an asynchronous task to load the module from the specified path. JSON imports only support default imports, so you need to access the default property to retrieve the values from the JSON file. Note the with statement defined by the import attributes specification when importing the file.

Using require in ESM

Starting with Node.js v18, you can mimic a require call to load JSON files in an ECMAScript module:

import {createRequire} from 'node:module';
const require = createRequire(import.meta.url);
 
function loadJSON(filename: string) {
  return require(filename);
}
 
This technique leverages `createRequire` from the `node:module` package to create a `require` function. This function emulates the behavior of CommonJS' require, offering an alternate method to import JSON data in ESM. This approach is particularly useful for developers transitioning from CommonJS to ECMAScript modules.
Back to Blog