reactjsnext.js

Cannot find module '@/components/my-components' in React Next.js app


I am creating a React app using Next.js and app routing. I'd like to create a separate file to hold the custom components I am creating. I noticed this Vercel template app does this using a components/ directory and then importing the components in the app using declarations like import { Chat } from '@/components/chat'

So, I created a components/ folder as well, giving me this file tree:

.
├── components /
│   └── my-components.tsx
└── src /
    └── app/
        └── page.tsx

However, when I try import {Component} from '@/components/my-components'; in page.tsx, I get the error: Module not found: Can't resolve '@/components/my-components'

How can I debug this further?

I also tried importing via path, e.g. import {Component} from './../../../components/my-components'; but that didn't work either


Solution

  • The @/ import alias is defined in your tsconfig.json file by the compilerOptions.paths key.

    If @/components/my-components doesn't work for you, it's because @/ is an alias for a folder other than your root folder. A common value used for this in Next.js projects is ./src/* which would mean TypeScript is trying to find your component at ./src/components/my-component.