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

Enforcing strict property validation on variables passed into TypeScript functions

Is there a method to enforce excess-property checking, not only for an inline object literal but also one derived from a variable? For instance, let's say I have an interface and a function interface Animal { speciesName: string legCount: nu ...

The API call for /api/users/create was resolved without a response, which could potentially lead to requests getting stuck. This issue was detected in

I've developed an API endpoint to manage user account creation within my Next.js application, utilizing knex.js for handling queries. Despite this, I keep encountering the following error: API resolved without sending a response for /api/users/create ...

Node C++ Addon Typescript declaration file

I have developed a Node C++ Addon that wraps a class similar to the one outlined in the official Node documentation. By using require(), I am able to access my addon and retrieve the constructor for my class in order to instantiate it. const { MyClass } = ...

Performing server operations within a client-side component using Next.js

I'm facing the challenge of needing to execute server actions on a client component because the shadcn/ui <Form> component necessitates it. I've been consulting documentation from shadcn/ui and Lucia. The shadcn/ui library utilizes react-ho ...

Exploring the process of selecting checkboxes in Angular 6

I'm currently learning Angular 6 and I have a requirement to mark checkboxes based on specific IDs from two arrays: this.skillArray = [ {ID: 1, name: "Diving"}, {ID: 2, name: "Firefighting"}, {ID: 3, name: "Treatment"}, ...

Using Angular 6 shortcodes in HTML

Is there a way to save an element in HTML as an alias for repeated use in Angular 6 without using *ngIf directive? For instance, consider the following code snippet: <dumb-comp [name]="(someObservable | async).name" [role]="(someObservable | a ...

The Unhandled Promise Rejection Warning in mocha and ts-node is due to a TypeError that arises when attempting to convert undefined or null values

I've been encountering issues while setting up ts-node with mocha, as the test script consistently fails. I attempted to run the following commands: mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ ...

Enhance the navigation scroll bar with a blur effect

I'm looking to create a navigation bar with a cool blur effect as you scroll. Everything seems to be working fine, except when I refresh the page the scrollbar position remains the same and window.pageYOffset doesn't give me the desired result. T ...

``There was an issue with the connection while fetching data using Nextjs middleware

I've encountered an issue where this code works perfectly fine in dev mode but fails when switched to production mode. Can anyone help me figure out what's causing the fetch failure? export default async function middleware(req: NextRequest) { ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Extract from Document File

After receiving a PDF through an Angular Http request from an external API with Content Type: application/pdf, I need to convert it into a Blob object. However, the conventional methods like let blobFile = new Blob(result) or let blobFile = new Blob([resul ...

Tips for reloading data with getServerSideProps and enabling data changes in NextJS pages

Imagine I have a webpage example.com/user/1 that has a single component receiving props through getServerSideProps, making it server-side rendered with prop values like {"name":"Bob"} This page allows the user to update the displayed n ...

Can data be cached from the server side using react-query and Next.js?

I'm exploring react-query for the first time and my webapp is built using nextjs with firebase. There are a few pages (projects.jsx and [id].jsx) that rely heavily on pre-fetched data from the server side. The issue is, they both fetch data from the e ...

What is the best way to compile TypeScript files without them being dependent on each other?

I have created a TypeScript class file with the following code: class SampleClass { public load(): void { console.log('loaded'); } } Now, I also have another TypeScript file which contains functions that need to utilize this class: // ...

Injectable error occurred while injecting one @Injectable() into another

I'm encountering an issue with Angular2 Dependency Injection. When attempting to inject one class into another, I am receiving the following error: Error Message: "Cannot resolve all parameters for 'ProductService'(undefined). Make sure tha ...

Leverage the power of openCv.js within your next.js projects

I am attempting to incorporate openCv.js into my next.js application a. I started the project with: npx create-next-app b. Next, I installed: $ yarn add @techstark/opencv-js c. Imported OpenCV with: import cv from "@techstark/opencv-js" d. Ho ...

Having trouble deploying through fab.dev because the Actions module is missing?

Currently, I am trying to deploy my next.js application via fab.dev onto Cloudflare Workers. However, I am encountering an issue where I am unable to successfully deploy the fab.zip file that is generated during the process. ...

What is the proper way to provide parameters for express.use to avoid encountering a type error?

When attempting to use the path string in this code snippet within the function, an error is thrown. The argument type string cannot be assigned to the parameter type RequestHandler<RouteParameters>    The assigned type does not contain call si ...

How to redefine TypeScript module export definitions

I recently installed a plugin that comes with type definitions. declare module 'autobind-decorator' { const autobind: ClassDecorator & MethodDecorator; export default autobind; } However, I realized that the type definition was incorrec ...

Struggling to establish a stable MQTT connection with Next.js? Many users have encountered errors and faced unstable connections. Read on

Currently, I am developing a real-time web application using next.js 14 along with the App router. In this project, I have integrated an MQTT connection that utilizes Mosquito under the hood. To establish the connection to the broker, I am leveraging the m ...