There seems to be an issue with executing an imported function from a .ts file within a TSX file in NextJs, resulting

I've encountered an issue that seems to be related to using NextJs with TypeScript.

For example:

// /pages/index.tsx

import _ from 'lodash' 

export const MyComponent = () => {
  return (
    <ul>
      {
        _.map(someArray, el => <li>{el}</li>) // Error: Module not found: Can't resolve 'fs'
      }
    </ul>
  )
}

This same error occurs with my custom functions as well, not just lodash functions.

When I import a function from a .ts file into my .tsx file and try to execute it within TSX, I receive a ModuleNotFound error. Sometimes I also encounter

ModuleNotFoundError: Module not found: Error: Can't resolve 'child_process'
. Interestingly, I can import and run a custom function imported from a .js file without any issues.

Here is my tsconfig.json configuration:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "...other options..."
  },
  "...other entries..."
}

Additionally, here is my package.json setup:

{
  "dependencies": {
    "@mdx-js/loader": "^1.6.22",
    "...other dependencies..."
  },
  "devDependencies": {
    "@types/lodash": "^4.14.172",
    "...other devDependencies..."
  }
}

In my next.config file, I use withMDX for handling MDX files:

const withMDX = require('@next/mdx')({
  extension: /\.mdx$/
})

module.exports = withMDX({
  pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
})

It seems like I may have overlooked something in configuring NextJs to work seamlessly with TSX and TypeScript. Any insights or solutions would be greatly appreciated!

Answer №1

Prefer to Resemble a Syntax Error

Your component needs to be returned with parentheses () to directly return JSX.

Additionally, import lodash functions by name like this:

import { map } from "lodash";
as it will aid in code-splitting

Thus, your component should look something like this:

import _ from "lodash";

export const MyComponent = () => {
  return (
    <ul>
      {_.map(someArray, el => (
        <li>{el}</li>
      ))
      }
    </ul>
  );
};

OR implicitly returned:

import _ from 'lodash';

export const MyComponent = () => (
  <ul>
    {_.map(someArray, el => (
      <li>{el}</li>
    ))
      }
  </ul>
);

OR you might not require using the lodash map in this scenario:

Simply utilize js Array.map

export const MyComponent = () => (
  <ul>
    {someArray.map(el => (
      <li key={el}>{el}</li>
    ))}
  </ul>
);

Answer №2

Typescript had no part in causing the error. The problem stemmed from using serialize outside of NextJS's pages directory while utilizing the next-mdx-remote package.

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

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Updating documents within an array in MongoDB is a common task that can be easily accomplished

Trying to modify a specific property within my MongoDB document. This is how the document is structured: "_id" : ObjectId("57e2645e11c979157400046e"), "id" : 1651570992420, "creator" : "nameHere ...

Refine the category based on a specified key

Currently, I am in the process of developing a React Hook using TypeScript. In this hook, I am passing both a key and a value that will be associated with this key as arguments. My objective is to constrain the type of the value based on the specified key. ...

Exploring the capabilities of Angular 4 with the integration of the Web

Trying to integrate the Web Speech API Interfaces (https://github.com/mdn/web-speech-api/) with an Angular application (version 4.25) and an ASP Core web server. The project is built using Visual Studio 2017 (version 15.7.1). Added @types/webspeechapi type ...

Is a donut chart graph visible on the webpage?

After successfully creating a bar chart, I decided to work on a donut chart using Angular and d3.js. However, despite creating the donut chart, I'm facing an issue with displaying it on the screen. The DOM shows that it is present, but for some reason ...

Error encountered following the upgrade of Angular and RxJS 5 to 6: Compilation failed

Since updating my libraries to the latest Angular 6 and RxJS 6, I've encountered an issue. I have a RouteService class that functions as a service. It utilizes the HttpClient to fetch data from a remote API. However, after the update, I'm facing ...

getStaticProps only runs on IIS after the entire page is refreshed

Using the nextjs getStaticProps feature in my project has been smooth sailing so far. However, after uploading the Static files to IIS, the feature seemed to stop working until I configured a urlRewrite module on it. I noticed that when initially visiting ...

A solution to the error message "Type 'unknown' is not assignable to type 'Country[]' in React TypeScript" is to explicitly define the type of the

I encountered error TS2322: Type 'unknown' is not assignable to type 'Country[]' pages/Countries/index.tsx Full code: import * as ApiCountries from '../../services/APIs/countries.api' function Countries() { const findCo ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

Encountering the error "ERR_HTTP_HEADERS_SENT" after attempting to send emails through the next.js API

Currently, I am in the process of generating users through the next.js API. However, my goal now is to utilize SendGrid for sending emails. The setup is in place, but unfortunately, I'm encountering the following issue: event - compiled successfully ...

Ways to resolve eslint typedef error when using angular reactive forms with form.value

I am facing an issue with my formGroup and how I initialized it. Whenever I try to retrieve the complete form value using form.value, I encounter an eslint error related to typecasting. userForm = new FormGroup<user>({ name: new FormControl<st ...

The application is having trouble accessing the property 'isXXXXX' because it is undefined

My attempt to utilize a shared service in one of my components has been successful when used with the app's root component. However, I encountered an error when trying to implement it on another module or dashboard. shared/authorize.service.ts @Inje ...

Why does the final value appear when passing an incrementing counter as a prop to multiple React Components created in a loop?

I am currently unraveling the concept of closures in JavaScript. Within this code snippet, I am cycling through the values of the 'items' array using a foreach loop. I have defined a let variable named "count" outside the scope of the loop. Afte ...

The ins and outs of Angular's type checking mechanisms

I have a few different scenarios on my mind. Imagine if I make an http call to fetch all movies from my php backend api. This is observable, so I need to subscribe to it. // Here's my service getAll() : Observable<Movie[]>{ this.http.get ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

Creating specific union types for a bespoke React hook

There are 4 objects with both similar and different keys. The union of these objects is used for database operations as follows -> type Objects = Food | Diary | Plan | Recipe ; A Custom Pagination Hook function usePaginate (key: string, options: Option ...

Convert C# delegate into TypeScript

Sample C# code snippet: enum myEnum { aa = 0, bb, cc, } public delegate void MyDelegate(myEnum _myEnum, params object[] _params); public Dictionary<myEnum , MyDelegate> dicMyDelegate = new Dictionary<myEnum , MyDelegate>(); publi ...

Vercel - Scheduled Tasks, Running Code exclusively during Deployment

Currently in the process of setting up a cron job on Vercel to test how our tasks, currently running on Heroku, perform on this new platform. Although the Usage report shows that the cron job is being triggered, I am unable to view the actual code executi ...