TechX
TechX

Reputation: 77

Why can't Next.js import files under a folder

Module not found: Can't resolve 'components/layout's Codes\nextjs-blog\pages\posts'
> 1 | import Layout from 'components/layout'
  2 | import Link from 'next/link'
  3 | import Head from 'next/head'

Ok so this is the error message I'm getting what's going anyone have an idea

I have my components folder under nextjs-blog and the js file that gives the error is under posts

I didn't give much info because I'm new to Next js and don't know what anyone would need

it doesn't work if I do

import Layout from '../components/layout'

Desktop/Marti's Codes/nextjs-blog <- this is the path to basic nextjs folder I've changed almost nothing to the folder in code and files

I have added components folder in the basic folder and in components I have two files : layout.js layout.module.js

then in pages I have posts folder and in there first-post.js which is the file importing the layout files from components

Upvotes: 2

Views: 5296

Answers (2)

TechX
TechX

Reputation: 77

It should be

import Layout from '../../components/layout'

Thanks to juliomalves for the answer

Upvotes: 3

Shyam
Shyam

Reputation: 1454

You need to use relative path to import components i.e. ../components/layout.

To use absolute imports like components/layout, we setup aliases like below in jsconfig.json.

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

and use like this

import Layout from '@/components/layout' 

Refer: https://nextjs.org/docs/advanced-features/module-path-aliases

Upvotes: 2

Related Questions