There was a problem locating the module .../node_modules/next/link' that was imported from ... Were you trying to import .../node_modules/next/link.js instead?

Struggling to package a React components library for my Next.js app, I'm faced with an elusive error that has left me perplexed. Despite experimenting with Rollup configurations, TypeScript compiler settings, and various tweaks to the package.json file over the past few days, I find myself at a loss. It seems like there's a missing piece of knowledge or experience on my end as I struggle to decipher the cryptic messages in the error log.

Server Error
Error: Cannot find module '/home/ola/Projects/lifeitself/flowershow/node_modules/.pnpm/file+packages+core+flowershow-core-0.0.4.tgz_wwvq4sry3mrfcince3djb3idna/node_modules/next/link' imported from /home/ola/Projects/lifeitself/flowershow/node_modules/.pnpm/file+packages+core+flowershow-core-0.0.4.tgz_wwvq4sry3mrfcince3djb3idna/node_modules/@flowershow/core/dist/index2.js
Did you mean to import <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7b9b2afa397e6e4f9e7f9e1">[email protected]</a>_biqbaboplfbrettd7655fr4n2y/node_modules/next/link.js?

This error occurred during page generation. View console logs in the terminal window.
Call Stack
new NodeError
node:internal/errors (387:5)
...

Context:

  • @flowershow/core is the TypeScript-written components library package
  • @flowershow/core acts as a dependency for`@flowershow/template
  • The monorepo, integrated with Nx (https://github.com/flowershow/flowershow), consists of both the core and the template packages structured as follows:
flowershow
├── packages
│   ├── ...
│   ├── core
|   |   ├── src
|   |   ├── project.json (Nx file)
|   |   ├── tsconfig.json
|   |   └── package.json
│   └── template
|       ├── ... typical Next.js app contents
|       ├── project.json (Nx file)
|       └── package.json
├── nx.json
├── package.json
├── pnpm-workspace.yaml
└── tsconfig.base.json

Relevant config files of @flowershow/core

package.json:

{
  "name": "@flowershow/core",
  "version": "0.0.4",
  "description": "Core Flowershow components, configs and utils.",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/flowershow/flowershow.git",
    "directory": "packages/core"
  },
  "author": "Rufus Pollock",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/flowershow/flowershow/issues"
  },
  "homepage": "https://github.com/flowershow/flowershow#readme",
  "publishConfig": {
    "access": "public"
  },
  "type": "module",
  "main": "./dist/index.js",
  "dependencies": {
    "@docsearch/react": "^3.3.0",
    ...
}

Answer №1

Lately, I've been delving deep into this issue as well. It seems that the pain experienced is due to a misconfiguration within Next.js itself in terms of exporting proper types for ESModules. This GitHub issue sheds light on the matter and leads to three more related GitHub issues which provide additional context: https://github.com/vercel/next.js/issues/46676#issuecomment-1451731653

My understanding is that the Next.js compiler has the capability to take your imported modules and bundle them together. Previously, there was a next-transpile-modules plugin that could be used in the next.config file, which is now integrated by default: https://nextjs.org/blog/next-13-1#built-in-module-transpilation-stable. By adding my package to this array in the configuration, I managed to get things running smoothly in dev mode but encountered failures in build mode no matter what I attempted.

Hence, it is hoped that this underlying issue will soon be addressed, or at least some guidance will be provided on how to properly bundle a component library for Next.js. I share a similar frustration where things don't seem to align as expected.

On further investigation, it appears that the culprit may be the "type: module" declaration in the package.json of the component library. Although there might be a workaround to make it function properly, during the build process of your Next app, everything gets transpiled down to commonjs format anyway. Perhaps it's not worth the effort to focus on bundling the component library extensively; just publishing one entrypoint and allowing Next.js to handle the rest might be a viable solution. While not entirely satisfying, this approach has enabled me to successfully run both in build and dev modes.

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

Having difficulty understanding Symbol.iterator and the return value type in a for-of loop while using TypeScript

Currently, I am delving into type script and embarking on a journey to learn how to craft generic containers for educational purposes. I have developed a LinkedList class with the intention of incorporating the ability to iterate over it, like so: for (co ...

Utilizing TypeScript function components within styled-components

I have developed a versatile component for displaying a DataGrid like this: interface Props<T extends unknown> { header: HeaderItem[] data?: T[], className?: string, children?: (row: T) => React.ReactElement[] } const DataGrid = & ...

Please come back after signing up. The type 'Subscription' is lacking the specified attributes

Requesting response data from an Angular service: books: BookModel[] = []; constructor(private bookService: BookService) { } ngOnInit() { this.books = this.fetchBooks(); } fetchBooks(): BookModel[] { return this.bookService.getByCategoryId(1).s ...

Encountering the ERR_TLS_CERT_ALTNAME_INVALID error in Next.js while using pm2

What is the solution for this error in Next.js? The project was deployed using PM2 and Nginx. Error [ERR_TLS_CERT_ALTNAME_INVALID]: The hostname/IP does not match the certificate's altnames. Host: scimagine.com. is not included in the cert's alt ...

Using Angular Typescript, implement a live chat feature that generates link previews

I am having trouble creating a link preview in live chat on my website. I want the preview of a dropped URL to show in the chat window, which requires extracting meta-data from the element of the resource (in that URL) like: <meta property="og:imag ...

Error: The argument provided cannot be assigned to a parameter that requires a string type, as it is currently a number

Currently, I am in the process of migrating some older websites to TypeScript. However, I keep encountering a type error during the build process. The specific error message is Type error: Argument of type 'number' is not assignable to parameter ...

Developing an object using class and generic features in Typescript

I am currently working on creating a function or method that can generate sorting options from an array. One example is when using Mikro-ORM, where there is a type called FindOptions<T> that can be filled with the desired sorting order for database q ...

How can a border be applied to a table created with React components?

I have been utilizing the following react component from https://www.npmjs.com/package/react-sticky-table Is there a method to incorporate a border around this component? const Row = require("react-sticky-table").Row; <Row style={{ border: 3, borderco ...

Unable to create a Next 13 application using react-quill

My NextJS app includes the react-quill library for rich text editing. Previously, I had no issues with importing the library dynamically to avoid server-side rendering problems. However, after upgrading to Next 13, I encountered a problem. During the bui ...

Unable to locate _app.js file in nextJs

Currently, I am utilizing npx create-next-app for generating my NextJs project and now I am looking to incorporate global styles using bootstrap Upon downloading bootstrap, the suggestion was to add global styles in pages/_app.js, but I couldn't loca ...

Error encountered in jquery.d.ts file: Unresolved syntax issue

I am currently in the process of transitioning my jQuery project into a Typescript project. I encountered an issue when attempting to include the jQuery typings from the DefinitelyTyped Github by using the following method: ///<reference path="../../ty ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...

Correct Way to Use 'useState' in Formik's 'onSubmit' Function?

I recently encountered an issue while using Formik in my Next.js application. Specifically, I am facing a problem with the submit `Button` component, which accepts a `showSpinner` prop to control its behavior. When set to true, the button is disabled and d ...

Unable to resolve error TS2532: The object may be undefined

I'm encountering an error in WebStorm with this code snippet. It's showing TS2532: Object is possibly 'undefined'. Despite installing both dotenv and @types/dotenv, the error persists. How can I resolve this issue? Check out the code b ...

Is it possible to call a service within an NgFor loop in Ionic/Angular 2?

I am facing an issue with my ngFor directive. Here is the code snippet: <ion-card *ngFor="let review of reviews"> <ion-card-content> {{getUserName(review.user_ID)}} </ion-card-content> </ion-card> The challenge I a ...

Guide for converting a JavaScript function with spread arguments of different types to C# style

I am having difficulty with the strict typing in C# when it comes to function arguments. For my Reverse Polish Notation (RPN) calculator, the required arguments will be passed through a function call using a comma-separated list of different types: this.F ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...

How can Jest be configured to test for the "permission denied" error?

In my Jest test, I am testing the behavior when trying to start a node http server with an invalid path for the socket file: describe('On any platform', (): void => { it('throws an error when trying to start with an invalid socket P ...

Trouble with Index.js: Posts not properly displaying in Sanity and NextJS

I completed the tutorial and reached the final section where I added the blog posts to a page. However, when I view the page, it only shows an H1 tag without any of the posts appearing. Can someone review the code and help me identify why it's not wor ...

How can we reduce the size of a JSON object in Typescript before sending it to the client?

Currently, I am faced with a common challenge. I have a database object that is a standard JS object originating from a document database, and my goal is to transmit this object to the client. However, certain fields contain sensitive information that shou ...