ยท 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:
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: