Relative imports on next app created with nx using VS Code

Viewed 1743

I'm facing an issue with a Next.js project bootstraped with nx and VS Code:

When I try to auto-import a component using VS Code, it will generate an absolute import which immediately triggers the @nrwl/nx/enforce-module-boundaries eslint rule, making the current file invalid.

For example, with folder structure:

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

The generated import will be:

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

While I expect:

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

VS Code has a setting to always use relative paths for imports, but that will prevent me from importing libraries in the proper way (@scope/lib).

Is there any possible setup that can make auto imports work as expected?

1 Answers

You can configure the paths property in the tsconfig.base.json file at the root of your project. If you add it to other tsconfig files it will not work, the correct one is the tsconfig.base.json file at the root of your project.

Going off of your example, you can add the following to the paths option.

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

Now you can change ../../../components/Loading to @my-app/components/Loading.

More detailed example (note: I've erased a bunch of the other options that should be in your tsconfig.base.json file for readability)

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

Source and more info in the official TS Handbook: https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

Related