What could be causing the import alias issue in the latest version of Next.js, version 12

Below are my CompileOptions:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": false,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    // "jsxImportSource": "@emotion/react",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["*"],
      "@/assets/*": ["assets/*"],
      "@/config/*": ["config/*"],
      "@/pages": ["pages/"],
      "@/public/*": ["public/*"],
      "@src/": ["src/"]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "src/**/*.ts",
    "src/**/*.tsx",
  ],
  "references": [
    {
      "path": "./tsconfig.node.json"
    }
  ],
  "exclude": ["node_modules"]
}

In the project structure, all listed paths are in the root directory. Despite this, I encounter the following error:

Cannot find module '@/src/containers/dashboard' or its corresponding type declarations.

https://i.stack.imgur.com/sWoho.png

After adding webpack config in next.config.js:

webpack(config) {
config.resolve.alias = {
  ...config.resolve.alias,
  '@': path.resolve(__dirname),
  '@/src/*': path.resolve(__dirname, 'src/*'),
};

The compilation is successful but errors still persist in VS code.

Answer №1

After making some adjustments to your configuration, I was able to get it working successfully. To start, make sure to update the baseUrl path to point to the src directory. Then, restart your TS Server using either Ctrl + Shift + P or F1 and selecting TypeScript: Restart TS Server.

{
  "compilerOptions": {
    "baseUrl": "src/",
    "paths": {
      "@/*": ["*"],
      "@/assets/*": ["assets/*"],
      "@/config/*": ["config/*"],
      "@/pages": ["pages/"],
      "@/public/*": ["public/*"],
      "@src/": ["src/"]
    },
  },
}

You should now be able to import your components as required:

import Header from "@/containers/dashboard";

If you have JavaScript files within your project that need to be imported, consider setting "allowJs": true in your configuration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why do I keep receiving a code parameter in the URL when using NextAuth with Patreon?

When using NextAuth with Patreon, I encountered an issue where after allowing access, I was redirected back to my URL with the "code" added as a parameter in the URL. From my understanding, NextAuth should handle this process automatically by passing the c ...

How to use TypeScript to set a value in ng2-ckeditor

I have implemented two ckeditor instances using *ngFor: <div class="form-group" *ngFor="let lang of languages"> <span>Legal text in {{lang.translate}} {{lang.abbr}}</span> <ckeditor id="{{lang.abbr}}" formControlName="{{lang.abbr} ...

Discovering the name of an object property by locating its corresponding id

I am working with a basic JSON data structure where I need to retrieve the name from an object by comparing its ID. For example, if I have the number 2, I need to check if it matches any object's ID. If the ID is equal to 2, then I must fetch the corr ...

I'm stumped - my URL path looks right, so why am I still getting a 404 error?

Having trouble with repeated 404 errors even though my URL path is correct. Here's the error message I keep encountering: FormSchema.tsx:49 POST http://localhost:3000/pages/api 404 (Not Found) app-index.js:33 Failed to submit form: Error: HTTP err ...

What is the process for loading a model using tf.loadModel from firebase storage?

I'm currently working on an app using the ionic3 framework that recognizes hand-drawn characters. However, I am encountering difficulties with importing the model into my project. The model was initially imported from Keras and converted using tensorf ...

The most efficient and hygienic method for retrieving a value based on an observable

Looking at the structure of my code, I see that there are numerous Observables and ReplaySubjects. When trying to extract a value from one of these observables in the HTML template, what would be the most effective approach? In certain situations, parame ...

What steps should I take to resolve the NextRouter "not mounted" error when deploying my Next JS 13 app on Vercel

I am encountering an issue while deploying my Next.js 13 app. The error message states: Module not found: Can't resolve 'encoding' in '/vercel/path0/node_modules/node-fetch/lib' Additionally, I am facing a "Next Router not mounte ...

Is it possible to set up TypeScript npm packages to be installed in their original TypeScript format rather than JavaScript for the purpose of examining the source code?

Despite my lack of expertise in the inner workings of how a TypeScript library compiles itself to JavaScript before being placed in the node_modules directory, I have a question: Coming from a PHP background, I am accustomed to being able to explore any l ...

Angular is notifying that an unused expression was found where it was expecting an assignment or function call

Currently, I am working on creating a registration form in Angular. My goal is to verify if the User's username exists and then assign that value to the object if it is not null. loadData(data: User) { data.username && (this.registrationD ...

Refreshing the page in React does not retain LocalStorage data when using Context

Managing state in my application using React Context and persisting data with LocalStorage has presented a challenge. Despite my efforts to maintain the stored data after a page refresh, I am facing an issue where the data is not retained as expected. here ...

Facing an "Invalid hook call" error in the NX monorepo with Next.js when trying to utilize jotai

Encountering a pesky "Invalid hook call" error while working on a Next.js app within an NX workspace. I've prepared this CodeSandbox. The start command fails when executed automatically, so manual rerun may be required. To replicate the issue, these ...

Leveraging the power of TypeScript and Firebase with async/await for executing multiple

Currently, I am reading through user records in a file line by line. Each line represents a user record that I create if it doesn't already exist. It's possible for the same user record to be spread across multiple lines, so when I detect that it ...

Redirect middleware for Next.js

I am currently working on implementing a log-in/log-out feature in my project using nextjs, redux-saga, and mui libraries. // middleware.ts import { NextRequest, NextResponse } from 'next/server'; import { RequestCookies } from 'next/dist/c ...

What is the best way to retrieve an object from a loop only once the data is fully prepared?

Hey, I'm just stepping into the world of async functions and I could use some help. My goal is to return an object called name_dates, but unfortunately when I check the console it's empty. Can you take a look at my code? Here's what I have ...

Introducing Next.js 13 - Leveraging Redis Singleton within Route Handlers

I have a basic library file that encapsulates some redis features: import Redis from 'ioredis' // Setting TTL to expire after an hour const TTL = 3600 console.log('Performing operations in redis.ts') const client = new Redis(process.e ...

Having trouble fetching data from Google's real-time database in a Next.js application

I am currently facing an issue with retrieving data from Google Realtime Database, and I am unsure of where the problem lies. The code snippet below is part of my Categories page: import CategoryHeader from '../../components/CategoryHeader'; impo ...

What are the risks of storing confidential keys in environment variables for a next.js application?

From my understanding, environment variables that start with NEXT_PUBLIC_ will be replaced with their values in the final bundle. Is it considered secure to include sensitive information like API keys and OAuth secrets using NEXT_PUBLIC_* variables, or is ...

Exploring Dynamic Linking and Routing in Next.js

I'm currently seeking the most effective method to link to a details page from a mapped list of objects. The API-fetching list is functioning properly, but I encounter an error when attempting to pass the ID to the details page. :3000/_next/static/d ...

What are the steps to troubleshoot server-side TypeScript code in NextJS with WebStorm?

I am struggling to debug the NextJS API in WebStorm while using TypeScript and navigating through the app route. It is proving to be quite challenging to efficiently debug the API without relying heavily on console.log(). ...

Utilizing a created OpenAPI client within a React application

Using the command openapi-generator-cli generate -i https://linktomybackendswagger/swagger.json -g typescript-axios -o src/components/api --additional-properties=supportsES6=true, I have successfully generated my API client. However, despite having all th ...