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

The variable 'data' is not a property of the type 'any[]'

I am currently facing an issue with a dummy service I created to fetch dummy data. When calling this service from a component ts file, I encountered the following error. After searching through some similar posts, I still haven't been able to resolve ...

Lazy-loaded modules in Angular that contain services provided within the module

Currently, I am facing a challenge with lazy-loaded modules and services that are provided in these modules. My folder structure looks like this: app -> featureModule1 (lazy loaded) -> featureModule2 (lazy loaded) -->services --->servi ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Upgrading from Sequelize V5 to V6: TypeScript bug - Property 'x' is not recognized in type 'y'

Updating from sequelize 5.x.x to 6.x.x has caused some issues for me. In version 5, everything was working fine but after the upgrade, I started facing TypeScript errors with properties generated via associations when trying to use objects from the include ...

Could Vercel's caching feature be causing any problems?

In my project, I am utilizing prisma/supabase with next js and hosting on vercel. Every time I make changes to my GitHub repository, a new development deployment is automatically generated on Vercel. Although everything seems to be running smoothly locally ...

What methods can I use to ensure that a user's credentials are not shown in the URL?

My NextJS application sometimes behaves unexpectedly. Whenever I have a slow connection and the initial load time of the site is longer than usual, after trying to log in to the application, the credentials I entered are displayed in the URL. This happens ...

Unable to assign to 'disabled' as it is not recognized as a valid attribute for 'app-button'

How to link the disabled property with my button component? I attempted to add 'disabled' to the HTML file where it should be recognized as an input in the button component (similar to how color and font color are recognized as inputs) ... but ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

What could be causing the images to not display on my HTML page?

My program is designed to display an image based on the result of the random function. Here is my HTML: <div> <h2>Player 0:</h2> <div id="MainPlayer0"></div> </div> Next, in my TypeScript fi ...

Encountered an error while trying to load config.ts file because of an issue

Trying to set up a new protractor project to conduct tests on an angular site. Node.js, typescript, protractor, and jasmine are all installed globally. After running webdriver-manager update and webdriver-manager start in the project folder, I proceed to b ...

What is the method to retrieve the data type of the initial element within an array?

Within my array, there are different types of items: const x = ['y', 2, true]; I am trying to determine the type of the first element (which is a string in this case because 'y' is a string). I experimented with 3 approaches: I rec ...

What is the standard procedure for verifying the authenticity of a value?

Currently, I am working on a social media application that requires users to create unique usernames. Technology Stack The technology stack consists of Next.js, Prisma, and MySQL (hosted by Planetscale). Within the application, Formik and Yup are used fo ...

How can I add an image to my Material-UI Next.js project?

After importing the image in this way: import img from '../public/buildingspattern.png' I then utilized it within the component like so: <Card className={classes.root}> <CardMedia className={classes.media} imag ...

On MacOS, VSCode encounters an issue with updating TypeScript imports when files are moved

I recently started transitioning a project from a mixed JS/TS setup to fully TypeScript. The project's server is hosted on AWS Lambda, and I have a tsconfig file at the root level as well as one in the /lambdas directory. One issue I've encounte ...

After making a change to a Vue or JavaScript file, running `npm run watch` causes a crash due to the `compileTemplate` function now requiring

I am facing an issue where both npm run dev and prod are functioning correctly, but when I attempt to run watch and make changes to files, npm run watch throws an error and crashes. I am using laravel mix with TypeScript, and my webpack mix parameters are ...

Is it necessary to retrieve all data from the database again after inserting just one item?

Currently, I find myself inside a Next.js application with both a form and a list of items. Upon submitting a new item through the form, it gets posted to the database and then appears in the list. My dilemma lies in whether it is more efficient to fetch ...

Utilizing Leaflet-geotiff in an Angular 6 Environment

I'm currently facing an issue where I am unable to display any .tif image on my map using the leaflet-geotiff plugin. I downloaded a file from gis-lab.info (you can download it from this link) and attempted to add it to my map, but I keep encountering ...

Wondering how to go back to the default locale in Next.js?

Within my Next.js application, I have successfully implemented the next-i18next module for multi-language support. The app currently supports two languages: English and Arabic, with English set as the default. To allow users to toggle between languages, I ...

Is there a way to incorporate margins into a React component using TypeScript?

I am currently facing a challenge in passing CSS attributes to a component that I am working with. The reason behind this is that I need to modify the margins to fit a specific space, hence my attempt to directly pass the margins. Does anyone have any sug ...