Troubleshooting path alias resolution issue in NextJS when using Typescript with index.ts files

I keep receiving a TypeScript warning stating that the module cannot be found.

This issue has surfaced while I'm utilizing TypeScript in my NextJS application, particularly when using custom paths. Previously, this problem never arose.

My project structure resembles the following:

/models
  |-- index.ts
  |-- User.ts
/pages
   /api
     /users
       |-- index.ts

I am attempting to import my Userschema from the custom path I defined in models, but encountering an error.

Here is how my index.ts file within models appears:

export { default as User } from './User';

This is how I am trying to import it inside api/user/index.ts:

import { User } from '@/models';

The contents of my tsconfig file are as follows:

{
    "compilerOptions": {
        "target": "es5",
        "lib": [
            "dom",
            "dom.iterable",
            "esnext"
        ],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": false,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "baseUrl": ".",
        "paths": {
            "@/components/*": [
                "./components/*"
            ],
            "@/types/*": [
                "./types/*"
            ],
            "@/utils/*": [
                "./utils/*"
            ],
            "@/middlewares/*": [
                "./middlewares/*"
            ],
            "@/models/*": [
                "./models/*"
            ],
            "@/lib/*": [
                "./lib/*"
            ]
        }
    },
    "include": [
        "next-env.d.ts",
        "**/*.ts",
        "**/*.tsx"
    ],
    "exclude": [
        "node_modules"
    ]
}

Importing using custom paths for non-index files like

import dbConnect from '@/utils/dbConnect'
functions properly. However, with index files, I still need to specify the index file name during import to make it work. For example:
import { User } from '@/models/index'

Answer №1

Resolved the issue by updating my path aliases configuration:

...
"baseUrl": ".",
"paths": {
    "@/*": [ "./*" ]
 }

Instead of setting up aliases for each folder separately, I opted for a universal alias which has resolved the problem.

Answer №2

If you're having trouble with the code above, then

{
  "compilerOptions": {
     // Using Absolute path in Next.js
    "baseUrl": ".",
    "paths": {

      // Add `/*` to access nested folder.
      // Omit `/*` for accessing `folder/index.ts`

      "@components": ["src/components"],
      "@components/*": ["src/components/*"],

      "@images": ["src/images"],
      "@images/*": ["src/images/*"],

      "@fonts": ["src/fonts"],
      "@fonts/*": ["src/fonts/*"]
    }
  },

This solution was provided in a Github issue thread.

Answer №3

Instead of:

        "baseUrl": ".",
        "paths": {
            "@/components/*": [
                "./components/*"
            ],
            "@/types/*": [
                "./types/*"
            ],
            "@/utils/*": [
                "./utils/*"
            ],
            "@/middlewares/*": [
                "./middlewares/*"
            ],
            "@/models/*": [
                "./models/*"
            ],
            "@/lib/*": [
                "./lib/*"
            ]
        }

Do:

        "baseUrl": ".",
        "paths": {
            "@/components/*": [
                "components/*"
            ],
            "@/types/*": [
                "types/*"
            ],
            "@/utils/*": [
                "utils/*"
            ],
            "@/middlewares/*": [
                "middlewares/*"
            ],
            "@/models/*": [
                "models/*"
            ],
            "@/lib/*": [
                "lib/*"
            ]
        }

This modification is necessary because all folders have already been specified with baseUrl:".". Now, you should refer to them using their respective aliases. This approach may seem peculiar, but it has been effective in resolving similar issues that I encountered before.

Answer №4

This dilemma had me stumped for quite some time. When utilizing the app router, I have the "components"-folder nested within my "app"-folder... This necessitates the following configuration:

{
  "compilerOptions": {
    "baseUrl": ".",
    /* ... */
    "paths": {
      "@/components/*": ["app/components/*"]
    }
   }
}

The baseUrl refers to the location of the package.json file and not where the components folder should reside. If you are using the app router with a "src"-folder, the setup would be as follows:

{
  "compilerOptions": {
    "baseUrl": ".",
    /* ... */
    "paths": {
      "@/components/*": ["src/app/components/*"]
    }
   }
}

Just a friendly tip for those who come across this in the future!

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 navigation bar on the web app is functioning properly on Android devices but experiencing a CSS problem on

My Nextjs web app includes a navbar with a hamburger menu, logo, and avatar. The navbar functions perfectly on desktop in Chrome, Mozilla, Brave (in developer tools mobile mode), and on Android phones using Chrome. However, when accessed from an iPhone X, ...

Is there a way to implement several filters on an array simultaneously?

Is it possible to filter an array based on both the input text from the "searchTerm" state and the selected option from the dropdown menu? I am currently using react-select for the dropdown functionality. const Positions = ({ positions }: dataProps) => ...

"webpack" compared to "webpack --watch" produces varying results in terms of output

My project is built on top of this setup: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html Running webpack compiles a bundle that functions correctly in the browser. However, running webpack --watch to recompile on file changes resul ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Leveraging a React hook within a Next.js API route

I am looking for a way to expose the data fetched by a React.js hook as a REST endpoint using Next.js. To create a REST endpoint in Next.js, I can easily use the code below in pages/api/index.tsx export default function handler(req: NextApiRequest, res: N ...

"Encountering an issue where attempting to set a property on an undefined variable, despite it being

I've been working on a timer app/component, but I'm running into an issue. The error message reads: Cannot set property startAt of undefined. I've defined it in my dashboard component, so I'm not sure where the problem lies. Any suggest ...

Guide to Triggering a Page View Event in Google Tag Manager with Angular

Previously, I manually fired the Page View Event using JavaScript from app.component.ts while directly accessing Google Analytics: declare var gtag: Function; ... constructor(private router: Router) { const navEndEvents = this.router.events.pipe( fil ...

Develop an integration of NextJS with .Net Core framework

Looking to develop a solution that integrates NextJS on the frontend and .NET6 on the backend within one unified setup for hosting on IIS10. While exploring Visual Studio 2022, I noticed a React template but encountered issues when trying to transition to ...

Automating email testing for Azure Graph-built applications: A step-by-step guide

I am exploring options to streamline the email testing process for an application developed with Azure Graph integration. Currently, I am leveraging playwright and typescript for other testing purposes within the application. One of the key functionaliti ...

Passing variables in Ionic's <a href> to open an external page: A step-by-step guide

I am trying to implement a feature in Ionic where I need to call a PHP page. In the home.html file, there is a URL being called like this - <a target="_blank" href="https://www.example.com?">pdf</a> The challenge now is to add a variable from ...

Having trouble launching the node pm2 process manager on AWS Elastic Beanstalk, npm update verification did not pass

Having some issues with utilizing pm2 for managing processes in my typescript node application, deployed on elasticbeanstalk. Whenever a new instance is launched by pm2, the following shows up in the logs ---------------------node.js logs---------------- ...

What is the process for incorporating personalized variables into the Material Ui Theme?

In the process of developing a react app with TypeScript and Material UI, I encountered an issue while attempting to define custom types for my themes. The error message I received is as follows: TS2322: Type '{ mode: "dark"; background: { default: s ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Why am I encountering difficulties running my Next.js project?

I have cloned projects that are 5 months old from GitHub and I am currently using Node.js version 18 or higher. Here is what I have tried: npx install cross-env //Tried installing and adding the following code to package.json "dev": "cross-env NODE_OPTI ...

The Angular program is receiving significant data from the backend, causing the numbers to be presented in a disorganized manner within an

My Angular 7 application includes a service that fetches data from a WebApi utilizing EntityFramework to retrieve information. The issue arises when numeric fields with more than 18 digits are incorrectly displayed (e.g., the number 23434343434345353453,3 ...

Initial loading of Nextjs SSG can be sluggish

After deploying my Nextjs app on Vercel, I noticed that the response time of SSG pages utilizing getStaticProps is slower during the initial page load, but subsequent loads are instant. This behavior has me puzzled and wondering why this delay occurs. I a ...

node-ts displays an error message stating, "Unable to locate the name '__DEV__' (TS2304)."

I recently inserted __DEBUG__ into a TypeScript file within my NodeJS project. Interestingly, in VSCode, no error is displayed. However, upon running the project, I encounter an immediate error: error TS2304: Cannot find name '__DEBUG__'. I att ...

What is the best method for automatically filling in the grid-cols-x property in tailwindcss grids

Currently, I am in the process of developing a page using NextJs and TailwindCss. In this project, users have the ability to upload an image from their local device and specify the number of pieces they would like the image to be split into horizontally an ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Tips for correctly invoking the init function of an external JS script upon page load in NextJS and Redux environmen

I am currently managing a website built with NextJS and Redux that is hosted on Vercel. A new feature we recently added requires a substantial amount of JavaScript code, so I decided to write it in a separate file and include it using the script tag withi ...