I am new to react & next and working with nextjs 13.5.3
I created a file at src/lib/db.js
importing in inner pages/api like this
import {connectionSrt} from "@/lib/db";
but which I run the application get this error
Module not found: Can't resolve '@/lib/db'
but when import like this, works fine
import {connectionSrt} from "../../../lib/db";
2
Answers
If you are using Typescript for React/Next.js project, you should consider tsconfig.json setting.
All of imports with alias(@) are configured by config.json setting.
Therefore, the setting should look like below.
Actually, do not care all of settings, but focus on "paths".
It makes Next.js to enable imports by alias(@).
Hope this helpful for you. 😊
The issue you’re experiencing is likely related to the way Next.js handles the path resolution and aliases.
The @ alias in your import statement (@/lib/db) is not being resolved properly by Next.js. This could be due to misconfiguration or lack of setup for the alias.
Here’s a step-by-step guide to set up path aliases in Next.js:
1.Configuring jsconfig.json (or tsconfig.json for TypeScript)
Create or modify your jsconfig.json (or tsconfig.json for TypeScript) file in the root directory of your project. This file helps define the path aliases for better import resolution.
Here, "@/": ["src/"] sets up the alias @ to resolve to the src directory.
2.Using the Alias in Your Imports
After setting up the alias, you can import modules using the defined alias:
Restart the Development Server