Using Visual Studio Code, the next app created with nx now supports relative imports

I am encountering a problem with a Next.js project set up using nx and VS Code:

When trying to automatically import a component in VS Code, it generates an absolute import which then triggers the

@nrwl/nx/enforce-module-boundaries
eslint rule, rendering the current file as invalid.

For example, consider the following folder structure:

apps/my-app/
  pages/
    entity/
      new/
        index.tsx
  components/
    Loading.tsx

The generated import looks like this:

// in my-app/pages/entity/new/index.tsx
import Loading from 'apps/my-app/components/Loading'

However, I expect it to be:

import Loading from '../../../components/Loading'

Although VS Code has a setting to always use relative paths for imports, it may prevent importing libraries in the appropriate manner (@scope/lib).

Is there any configuration that can ensure auto imports function as expected?

Answer №1

To set up the paths property in your project, navigate to the tsconfig.base.json file located at the root directory. It's important to only include this configuration in the main tsconfig.base.json file, as it won't work properly if added to other tsconfig files.

For example, you can update the paths option with the following:

"@my-app/*": ["apps/my-app/*"]

Once configured, you can easily replace instances of ../../../components/Loading with @my-app/components/Loading.

Here is a simplified version of the setup within the tsconfig.base.json:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@my-app/*": [
                "apps/my-app/*"
            ]
        }
}

For more information and additional details, refer to the official TypeScript Handbook: https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

Answer №2

For those encountering unresolved issues related to nx monorepo usage:

Troubleshooting two common errors (TS error and lint error):

Firstly, addressing the Alias error:

Unable to locate module '@account/components/something' or its type declarations.

  1. In your base tsconfig.base.json file (not the tsconfig.json under your apps, as it gets overridden), include:
"compilerOptions":{
       ...
       baseUrl:"." // Consider using "src" if relevant for boiler plates or missing path resolution on the error message.
       paths: {
       "@account/*": ["app/*"],
       "@account/components/*": ["app/components/*"] 
     }
   },

The above configuration will resolve:

import { authMiddleware } from '@account/components/something';

to

import { authMiddleware } from '../../../components/something';

Regarding the lint error:

Projects should use relative imports to import from other files within the same project - eslint rule @nrwl/nx/enforce-module-boundaries fails`

  1. Set "allowCircularSelfDependency" to true.
"@nrwl/nx/enforce-module-boundaries": [
          "error",
          {
            "allowCircularSelfDependency": true, -> This might resolve the lint error.
            "allow": ["@account/**"], -> // Whitelist the lint error.
             ...
          }
  1. Specify allowed folders: Include "allow": [@foldername]
"@nrwl/nx/enforce-module-boundaries": [
          "error",
          {
            
            "allow": ["@account/**"], -> // Whitelist the lint error.
             ...
           }

These steps should help resolve the issues.

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

What is the best way to store a small number of files in the state

I have recently implemented Drag and Drop functionality, and now I am facing an issue where I need to save a few files in state. const [uploadedFiles, setUploadedFiles] = useState<any[]>([]); const onDropHandler = async (e: React.DragEvent<HTMLDi ...

Is there a way to enforce a mandatory lambda argument?

I am trying to pass a lambda into a function, but I need the lambda to have only one argument. TypeScript correctly generates an error if I provide two parameters to the lambda, however it does not raise any issues if I leave out any arguments altogether ...

Custom React hook that returns an array of custom components

Do you think this approach using custom hooks is efficient? I'm providing an array as input and then iterating through it to decide which components should be shown. import React from "react"; import { Image, Paragraph, Header } from " ...

Dragging element position updated

After implementing a ngFor loop in my component to render multiple CdkDrag elements from an array, I encountered the issue of their positions updating when deleting one element and splicing the array. Is there a way to prevent this unwanted position update ...

Can a client receive a response from server actions in Next.js 13?

I'm currently developing a Next.js application and I've created an action in app/actions/create-foo-action.js. In this server action, I am attempting to send a response back to the client. import { connectDB } from "@utils/database" imp ...

Managing TypeScript objects

Just starting out with TypeScript and feeling a bit lost. The data I receive from my BackEnd looks like this: { "A": [ { "fieldA": 0, "fieldB": "A", "fieldC": ...

Integrate service once the constructor has completed execution

I created a service to connect with the Spotify API. When initializing this service in the constructor, it needs to retrieve the access token by subscribing to an Observable. However, there's an issue: The service is injected into my main component ...

The 'HTMLDivElement' type does not include the property 'prepend' in Typescript

When working with a typescript method, the following code snippet is used: some_existing_div.prepend(some_new_div) This may result in an error message: [ts] Property 'prepend' does not exist on type 'HTMLDivElement'. However, despi ...

TS2531: Nullability detected in object when using .match() method

I'm encountering a linting error on fileNameMatches[0] in the following code snippet. Strangely, the error doesn't appear on the Boolean() check. Even if I remove that check, the issue remains unresolved. Can anyone suggest a solution? protected ...

The type 'MenuOptions[]' cannot be assigned to type 'empty[]'

Even after numerous attempts, I am still grappling with TypeScript problems. Currently, I am at a loss on how to resolve this particular issue, despite all the research I have conducted. The code snippet below is what I am working with, but I am struggling ...

Issue with executing a server-side function in a Next.js application

I'm encountering an issue with my Next app. I have a method in my ArticleService class that retrieves all articles from my SQL database. async getArticles(): Promise<IArticle[] | ServiceError> { try { const reqArticles = await sql< ...

Ways to retrieve specific Observable elements?

Having a function like this: getCategories(): Observable<any> { return this.category.find({where: {clientId: this.userApi.getCurrentId()}}) }; The return type of this.category.find is Observable<T[]>. When I invoke g ...

The NgModel function within *ngFor is executing more times than necessary during initialization

Displayed on screen are a list of tutorials with check boxes next to each tutorial's states. These tutorials and states are pulled from the database, each tutorial containing a name and an array of associated states. Here is the HTML code: <div c ...

When working with esbuild in AWS Amplify, an error occurs with the invalid build flag -rw-r--r

I've been working on hosting a Next.js project in AWS Amplify, but I encountered an issue due to the size of my app exceeding the Amplify limit. To address this, I had to utilize the following command to minimize the size of my app during the build pr ...

data retrieval not refreshing sorting post construction

My challenge involves fetching data from MongoDB with sorting. While it works perfectly on the development server, it fails to update the data after being built and hosted. import Review from "@/models/review"; import connectdb from "@/util/ ...

What is the reason for VS Code recognizing an import as valid while WebPack does not approve it?

I believe the root of the problem lies in the version of WebPack I am using ("webpack-cli": "3.3.11"). Before embarking on another round of debugging to upgrade WebPack (attempted version 5 but faced issues due to lack of a config file) ...

The combination of TypeScript output is not working as expected

Here is my current configuration: tsconfig.json { "compileOnSave": true, "compilerOptions": { "module": "none", "outFile": "js/app.js" } } MyApp.Main.ts class Main { constructor() { Utilities.init(this); ...

Issue with Angular 6: Struggling to Implement DatePipe

I am trying to set the current date within a formGroup in a specific format, but I keep encountering an error with the code below: 'Unable to convert "13/07/2020" into a date' for pipe 'DatePipe' this.fb.group({ startdateActivi ...

Some devices are experiencing issues with their camera not turning on during Next.js and Socket.IO video chats

Upon integrating video chat into my existing Next.js application, I encountered two specific issues. My tech stack includes Next.js version 10, socket.io version 4, socket.io-client version 4, and express. Being a novice in this area, I researched variou ...

Angular allows for creating a single build that caters to the unique global style needs of every

Currently, I am working on a project for two different clients, each requiring a unique style.css (Global CSS). My goal is to create a single production build that can be served to both clients, who have different domains. I would like the global style t ...