skip to Main Content

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


  1. 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.

    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "bundler",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "incremental": true,
        "plugins": [
          {
            "name": "next"
          }
        ],
        "paths": {
          "@/*": ["./src/*"]
        }
      },
      "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
      "exclude": ["node_modules"]
    }
    

    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. 😊

    Login or Signup to reply.
  2. 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.

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

    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:

    import { connectionSrt } from "@/lib/db";
    

    Restart the Development Server

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search