Using typescript, encountering an issue with dynamic import and json file integration

When creating a function to retrieve test data for multiple environments, I encountered an issue:

export class DataHelper {
  public static async getTestData(fileName: string): Promise<any> {
    return await import(`../${fileName}`);
  }
}

Running this code resulted in the following error: Error: Cannot find module '../test-data.json'

await DataHelper.getTestData('test-data.json')

However, the following calls were successful:

await DataHelper.getTestData('TestScript')

And also:

await import('../test-data.json')

This is the content of my tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "sourceMap": true,
    "outDir": "./lib",
    "moduleResolution": "node",
    "baseUrl": ".",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true
  },
  "include": ["src", "example/**/*"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

I am seeking clarification on what is causing this issue and what corrective actions should be taken. Any insights would be greatly appreciated.

Answer №1

To dynamically import JSON files in TypeScript, you need to utilize import assertions as TypeScript does not natively support importing json files like JavaScript. This can be confusing for many users due to the difference between TypeScript and JavaScript specifications. Here is an example of how import assertions are used, although they are currently not supported on Node.js:

// static import
import data from "./foo.json" assert { type: "json" };

// dynamic import
const { default: data } = await import("./foo.json", { assert: { type: "json" } });

In summary, imports must be asserted because relying solely on file extensions to determine file types poses security risks.

For now, a reliable method to asynchronously retrieve JSON data in Node.js is by reading the text using fs and then utilizing JSON.parse. It may take some time before Node.js supports import assertions on stable versions.

Here's an illustration of this process:

import { readFile } from "fs/promises";

async function readJsonFile(path) {
  const file = await readFile(path, "utf8");
  return JSON.parse(file);
}

readJsonFile("./package.json").then((data) => {
  console.log(data);
});

Answer №2

The Typescript thread discusses the discontinuation of support for importAttributes "assert" due to a regression from stage 3 to stage 2.

There have been talks about replacing it with "why" for several months now.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to simulate an initialized class within a function without using dependency injection

Creating a unit test for a service that utilizes aws-sdk to retrieve all files from an s3 bucket poses a challenge. Within the function, the S3 class is instantiated and listObjectsV2 is used to fetch files from the bucket. For testing purposes, it's ...

Defining a property of an object within a Vue Class

If I were to write it in JavaScript version: export default { data() { return { users: {} } } } However, when using a class style component with vue-property-decorator: @Component export default class Login extends Vue { public title ...

When the async keyword is added, the return type in Typescript can vary

This situation is really puzzling to me. I wrote a function to calculate the number of documents in a collection getDocCount(): Promise<number> { return MyModel.countDocuments({}); } Everything seemed fine. However, when I removed async since I ...

When you use array[index] in a Reduce function, the error message "Property 'value' is not defined in type 'A| B| C|D'" might be displayed

Recently, I delved deep into TypeScript and faced a challenge while utilizing Promise.allSettled. My objective is to concurrently fetch multiple weather data components (such as hourly forecast, daily forecast, air pollution, UV index, and current weather ...

What steps can be taken to address the InvalidPipeArgument error when working with dates?

When attempting to format a date in a specific way using the pipe date, I encountered an error: Uncaught Error: InvalidPipeArgument: 'Unable to convert "25/01/2019" into a date' for pipe 'e' at Xe (main.fc4242d58c261cf678ad.js:1) ...

Currently honing my skills in Angular 2, but encountering an error stating "Bindings cannot contain assignments."

<app-employeecount [all]= "gettotalemployeescount()" <app-employeecount [all]= "gettotalemployeescount()" [male]= "gettotalmaleemployeescount()" [female]="gettotalfemaleemployeescount()" (on ...

TypeORM - Establishing dual Foreign Keys within a single table that point to the identical Primary Key

Currently, I am working with TypeORM 0.3.10 on a project that uses Postgres. One issue I encountered is while trying to generate and execute a Migration using ts-node-commonjs. The problem arises when two Foreign Keys within the same table are referencing ...

How to dynamically assign a value in a React datepicker component in a React application

Having troubles with react-datepicker? I encountered an issue where setting the value of react-datepicker from props caused it to either not show the value or display a 'wrong time format' error. Here is a snippet of the Datepicker code: this.sta ...

The image map library functions seamlessly with React but encounters issues when integrated with Next.js

I have been working on a client project that requires the use of an image map. I searched for a suitable library, but struggled to find one that is easy to maintain. However, I came across this particular library that seemed promising. https://github.com/ ...

What steps can be taken for TypeScript to identify unsafe destructuring situations?

When working with TypeScript, it's important to prevent unsafe destructuring code that can lead to runtime errors. In the example below, trying to destructure undefined can cause a destructuring error. How can we ensure TypeScript does not compile suc ...

Utilizing *ngIf for Showing Elements Once Data is Completely Loaded

While working on my Angular 2 app, I encountered an issue with the pagination UI loading before the data arrives. This causes a visual glitch where the pagination components initially appear at the top of the page and then shift to the bottom once the data ...

React Component not displaying properly when used inside a map iteration

I am currently working on rendering multiple components using the .map method on an array with specific content. Although I can't find any errors in the console, the component is not appearing in the DOM as expected. I attempted to set subHeader to nu ...

Troubleshooting the ReferenceError: Blob is not defined problem with the heic2any library in a Next.js application

Currently, I am encountering an issue where everything is properly implemented and functioning smoothly. However, the main problem arises when I attempt to reload the page, as it results in an error message: ReferenceError: Blob is not defined. This issue ...

Which is more efficient: Storing the database as a private member variable in Ionic 3 SQLite or creating a new database for every query

Here's a question for you - in the context of Ionic 3, what would be the preferable approach: keeping the opened database as a private member variable within a database provider class, or calling create every time a query is made to the database? For ...

Developing in TypeScript with styled-components allows for seamless integration between

New to TypeScript and seeking guidance. I currently have a component utilizing styled-components that I want to transition to TypeScript. import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-comp ...

A collection of objects in TypeScript with a reference and the ability to add new objects using the

Recently, I've come across an issue in my code while working with custom objects and arrays of them. I have identified a scenario where the push() method works fine and another where it doesn't. Scenario 1 (working as expected): class MyObject{ ...

Tips for ensuring all files are recognized as modules during the transition of an established NodeJS project to TypeScript

I'm diving into TypeScript as a newcomer and I am exploring the process of transitioning a large, existing NodeJS codebase that is compliant with ES2017 to TypeScript. Here's a glimpse at my tsconfig.json: { "compilerOptions": { "mo ...

How come the useEffect hook is causing re-rendering on every page instead of just the desired endpoint?

I am a novice attempting to retrieve data from a database and display it on the front-end using Axios, ReactJS, and TypeScript. My intention is for the data to be rendered specifically on localhost:3000/api/v1/getAll, but currently, it is rendering on all ...

What is the reason behind the slight difference between TypeScript's IterableIterator<> and Generator<> generics?

In TypeScript version 3.6.3, there is a notable similarity between Generator<> and IterableIterator<>. However, when Generator<> extends Iterator<>, the third generic argument (TNext) defaults to unknown. On the other hand, Iterator ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...