Getting a "module not found" error in Next.js while trying to import a TypeScript

Check out this code snippet:

// lib/customFunction.ts

export function customFunction() {
  console.log("customFunction");
}
// pages/homepage.tsx

import { GetServerSideProps } from "next";
// works
import { exampleFunction } from "../lib/exampleFile.js";
// error
import { customFunction } from "../lib/customFunction.js";

export const getServerSideProps: GetServerSideProps = async ({
  req,
}): Promise<{ props: {} }> => {
  exampleFunction();
  customFunction();
  return { props: {} };
};

export default function Homepage(props: {}) {
  return <div>Hello World</div>;
}

When running this code, I encounter the following issue:

Module not found: Can't resolve '../lib/customFunction.js' in '/Users/USER/Documents/software/nextjs-test/pages'

I am puzzled by this. Shouldn't lib/customFunction.ts compile to lib/customFunction.js, and the import should work correctly? I guess my understanding of how TypeScript handles imports is limited.

You can find all the code at: https://github.com/arcticmatt/nextjs-test

Answer №1

Let me break down what's going on here.

webpack is encountering a ModuleNotFoundError within Compilation.js.

This issue arises because webpack is responsible for compiling TypeScript into JavaScript. More information on this topic can be found in this article.

If you insert the following code block into your next.config.js file:

module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    console.log(config);
    config.module.rules.map((rule) => console.log(JSON.stringify(rule)));
    return config;
  },
};

You will be able to view the webpack configuration used by Next.js. It appears that they utilize the next-babel-loader to convert TypeScript to JavaScript before bundling it.

In essence, the problem unfolds as follows:

  1. webpack attempts to locate ../lib/test2.js within Compilation.js, prior to any JavaScript compilation occurring.
  2. ../lib/test2.js does not exist since ../lib/test2.ts has yet to be compiled into JavaScript.
  3. Consequently, an error is triggered.

The remedy involves omitting the file extension and using

import { test2 } from "../lib/test2";
. Feel free to clone the repository referenced in the original post and execute yarn dev to confirm this solution works correctly.

Answer №2

To get started, simply add the necessary babel packages to your project. More information can be found at this link: https://www.npmjs.com/package/babel-loader.

npm install -D babel-loader @babel/core @babel/preset-env webpack

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

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

What steps should I take to resolve the "You do not have authorization to access this directory or page" error in Azure App Services?

Currently, I am attempting to deploy my Next.js 13 application to AppServices using Github Actions. The compilation process on Github was successful, however, I am encountering an issue where my application does not seem to be deploying or starting up prop ...

Encountering a 404 error when utilizing ngx-monaco-editor within an Angular application

I have been encountering an issue while attempting to utilize the editor within my Angular 8 application. Despite researching similar errors on Stack Overflow and GitHub discussions, I haven't found a solution yet. Here's how my angular.json asse ...

Testing route changes in NextJS, Vitest, and React Testing Library: A comprehensive guide

Looking for advice on how to effectively test routing in a NextJS app that functions as a static site generator without server-side rendering capabilities. Specifically, I need help testing the entire application's routing. For example, if my site beg ...

When trying to attach a volume from a local directory to a next.js container, a TypeError occurs stating that Object(...) is not a function

Currently, I am attempting to connect a local volume directory for Next.js/React's hot reload feature during development. The configuration in my docker-compose.development.yml file is as follows: services: web: command: next dev volumes: ...

The proper method for referencing TypeScript compiled files with the outDir option

I am currently working on a simple app that consists of two .ts files. These files are compiled using the following tsconfig.js file: { "compilerOptions": { "target": "ES5", "module": "commonjs", "sourceMap": true, "emitDecoratorMetadata ...

Oops! Looks like there's an unexpected error with the module 'AppRoutingModule' that was declared in the 'AppModule'. Make sure to add a @Pipe/@Directive/@Component annotation

I am trying to create a ticket, but I encountered an error. I am currently stuck in this situation and receiving the following error message: Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Plea ...

It appears that TypeScript is generating incorrect 'this' code without giving any warning

I seem to be facing some resistance filing a feature request related to this on GitHub issues, so I'll give it a shot here. Here is the code snippet that caused me trouble: export class Example { readonly myOtherElement: HTMLElement; public ...

Error with declaring TypeScript class due to private variable

When defining a TypeScript class like this: export class myClass { constructor(public aVariable: number) {} private aPrivateVariable: number; } and trying to initialize it with the following code: let someVar: myClass[] = [{ aVariable: 3 }, { aV ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: string, value ...

Unable to modify font weight - Choose Ant Design Select Component

I'm new to programming and I'm working on creating a select component using ant-design. However, I am facing an issue where I cannot change the font-weight within ant-design. The component seems to accept all other properties that are passed exce ...

Limiting User Access on ReactJS Routes

Is there a way to restrict user routes in my application? I want to prevent users from manually typing URLs into the address bar, for example: http://localhost:3000/admin if they are already on https://localhost/users. Only users with admin privileges shou ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

The predeploy function encountered an error: Command ended with a non-zero exit code of 2 due to an "import issue"

Currently, I am in the process of learning how to utilize Cloud Functions for Firebase with TypeScript. Unfortunately, I have hit a bump in the road when attempting to deploy Firebase. If you take a look at Vscode, you'll see what I mean: The error m ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

What are the steps to repurpose a domain that is currently in use on Vercel?

Currently managing a blog on Next.js at my website thisishaneum.com. However, I am interested in creating a separate portfolio page that is distinct from the blog content. I attempted to set up a new page by adding a 'portfolio' directory within ...

Experimenting with TypeScript Single File Component to test vue3's computed properties

Currently, I am in the process of creating a test using vitest to validate a computed property within a vue3 component that is implemented with script setup. Let's consider a straightforward component: // simple.vue <script lang="ts" set ...

Angular is having trouble with the toggle menu button in the Bootstrap template

I recently integrated this template into my Angular project, which you can view at [. I copied the entire template code into my home.component.html file; everything seems to be working fine as the CSS is loading correctly and the layout matches the origina ...

Addressing the data transfer issue between Spring framework and Next.js using Axios

For my upcoming project, I am considering using a combination of Spring and Next.js. In the past, I have worked on projects using Spring and React. I find the API/route structure in Next.js 13 version to be quite intriguing compared to traditional React ...

Encountering "Undefined error" while using @ViewChildren in Angular Typescript

In my application, I am facing an issue with a mat-table that displays data related to Groups. The table fetches more than 50 rows of group information from a data source, but initially only loads the first 14 rows until the user starts scrolling down. Alo ...