Alias Imports Suddenly Caused Module Not Found Errors in NextJS

I am building a NextJS app and all of a sudden all my import aliases stopped working

This is my jsconfig.json

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

I have an initial import like this in my layout.jsx file:

import {RootLayout} from '@/components/RootLayout';

And that stopped working completely.

I had to go through my project and use absolute paths so I turned that into:

import {RootLayout} from '/src/components/RootLayout';

And everything is loading but does anyone have any ideas what happened? I can't get my alias to work now.

Im using Linux, Visual Studio Code, Nginx, on a DO Droplet.

I tried to use @/components/RootLayout but received a Module not found - my aliases broke and they had been working for days before?

Upvotes: 3

Views: 2102

Answers (6)

rukonbd
rukonbd

Reputation: 1

modify tsconfig.json file

{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "./*"
      ]
    },
    //other options go here
}

Upvotes: -1

DanB-Web
DanB-Web

Reputation: 45

I had this issue (Next 14) once I started migrating some files over to TS - I think the tsconfig is overwriting the jsconfig.

Moving my compiler options to the tsconfig and restarting the dev server solved my issues.

Upvotes: 1

Charles Kellogg
Charles Kellogg

Reputation: 31

I had a similar issue. It started after I created a page file called page.tsx instead of page.jsx.

Apparently adding a TypeScript file in the app directory causes a tsconfig.json file to be generated in the root directory of the project which seemingly overrode the jsconfig.json file. The tsconfig.json file did not have the "paths" object with the alias.

Deleting the tsconfig.json file fixed the issue.

Upvotes: 3

raajesh297
raajesh297

Reputation: 11

Found a weird behaviour though, using my parent package's import alias inside module's code worked.

In my parent I use an alias ~components. In my module I use @/components. Now I use ~components inside my module for it to work.

Other way to fix is to add the newer variant of import in the parent's jsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "jsx": "react",
    "paths": {
      "~*": [ "src/app/*" ],
      "@/*": [ "src/app/*" ], // Add this module's alias in parent
    }
  },
}

Upvotes: 0

Badis Kefi
Badis Kefi

Reputation: 11

this happened to me too, what i did was deleting node-modules and npm i again , that solved the issue, i'm not sure why this happened exactly but i guess it is because my computer is old and slow so it caused errors to happen.

Upvotes: 0

Jbbae
Jbbae

Reputation: 1038

Also seeing this all of a sudden starting today...

Here is my jsconfig.json:

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

I can't for the life of me figure out why this is happening...

Upvotes: 1

Related Questions