Issue with tsconfig path alias not resolving when paths are outside of the baseUri

I've encountered an issue in my monorepo where the tsconfig doesn't resolve paths that are located above the current project directory.

Here's an overview of my project structure:

── apps
│   ├── sahl
│   │   ├── index.d.ts
│   │   ├── jest.config.ts
│   │   ├── next-env.d.ts
│   │   ├── next.config.js
│   │   ├── project.json
│   │   ├── public
│   │   ├── src
│   │   ├── tsconfig.json
│   │   └── tsconfig.spec.json
├── libs
│   └── shared
│       ├── data-access
│       └── zod-types
├── nx.json
├── openapi.json
├── package.json
├── pnpm-lock.yaml
├── prisma
│   └── schema.prisma
├── tools
│   ├── database
│   ├── tsconfig.tools.json
│   └── zod-to-openapi.ts
└── tsconfig.base.json

My goal is to grant the directories in the "apps" folder access to files in the "libs/shared" directory.

Initially, I attempted to add these paths in tsconfig.base.json and extend them to the tsconfig.json of apps/sahl:

// ./tsconfig.base.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "paths": {
      "@libs/*": ["./libs/**/*.ts"],
    }
  },
  "exclude": ["node_modules", "tmp"],
  "include": ["./libs/shared/data-access/*.ts", "./libs/shared/zod-types/modelSchema/*.ts"],
}

However, it seems that the extension functionality of tsconfig is more of an overwrite than the merge I expected after further investigation.

Subsequently, I tried to include those paths and includes in the child tsconfig.json:

{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    // Compiler options here
  },
  "include": [
    // Included paths here
  ],
  "exclude": [
    // Excluded paths here
  ]
}

Despite these efforts, I am facing difficulties with tsc not resolving the paths correctly during build time. It's puzzling as vscode and the "dev" functionality (e.g., next dev) are still functioning properly and recognizing the paths.

If anyone has any insights or suggestions, I would greatly appreciate it!

EDIT

Following @jagmitg's advice, I have removed baseUri from the child tsconfig.json to circumvent conflicts:

// apps/sahl/tsconfig.json

{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    // Compiler options here
  },
  "include": [
    // Included paths here
  ],
  "exclude": [
    // Excluded paths here
  ]
}

and instead designated it in tsconfig.base.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    // Compiler options here
  },
  "exclude": [
    // Excluded paths here
  ],
  "include": [
    // Included paths here
  ]
}

As a result, I encountered a new error message:

- info Creating an optimized production build...
       Failed to compile.
       
       ./src/app/api/articles/[articleId]/route.ts
       Module not found: Can't resolve '@libs/shared/data-access/articles.data'

Could it be due to a typo or incorrect relative path in the includes?

Answer №1

Consider including a baseUrl in your tsconfig.base.json file that points to the root of your repository.

Avoid changing the baseUrl in any child configurations to ensure the path mapping from the base config remains valid.

Here is an example of how the base config should be structured:

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

As for the child config, it should be similar to this:

{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    // Do not override the baseUrl here
    "rootDir": "../../",
    // ...
    "paths": {
      "@/": ["./apps/sahl/src/*"],
      "@/styles/*": ["./apps/sahl/src/styles/*"],
      "@/types/*": ["./apps/sahl/src/types/*"],
    }
  },
  // ...
}

UPDATE:

One solution to this issue is to consider using the babel-plugin-module-resolver.

Include the following in your .babelrc file:

{
  "presets": ["next/babel"],
  "plugins": [
    ["module-resolver", {
      "root": ["./"],
      "alias": {
        "@libs": "./libs"
      }
    }]
  ]
}

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

Redeeming tokens from different origins is only allowed for clients classified as the 'Single-Page Application' type

I've encountered an issue while trying to obtain an access token from the MS Graph API within a Next.js application. Everything works perfectly in Postman, but when attempting it in my app, I receive the error message: "AADSTS9002326: Cross-origin tok ...

Having trouble getting a React Hook to function properly in NextJS with TypeScript. Let's troubleshoot

I'm currently utilizing NextJS to showcase information fetched from a database in a table format. After retrieving the data, my intention is to leverage the map function to generate table rows and then incorporate them into the table. import React, {u ...

Bringing in information from a TypeScript document

I'm having trouble importing an object from one TypeScript file to another. Here is the code I am working with: import mongoose from "mongoose"; import Note from './models/notes'; import User from './models/users'; import ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Passing a boolean as the value for a Material UI MenuItem in a React TypeScript application

I am encountering an issue as a beginner in react with passing a simple boolean value as a prop for the MenuItem component in the material UI library. I believe the solution is not too complex. Can someone provide guidance on how to fix this error? The sp ...

Error: XYZ has already been declared in a higher scope in Typescript setInterval

I've come across an interesting issue where I'm creating a handler function and trying to set the current ref to the state's value plus 1: const useTimer = () => { const [seconds, setSeconds] = useState(0); const counterRef = useRef(n ...

Next.js continues to generate a 404 error page instead of displaying the details of the blog post

I am having trouble with generating my blog details page as I keep getting a 404 error. The data is being fetched from a headless cms called contentful. Below is the structure of my files and code: https://i.stack.imgur.com/kK8B6.png Additionally, here i ...

What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...

Having trouble with updating React state? The useEffect hook runs when attempting to change the state, but it seems to have the

Having worked with useEffect and its ability to trigger after a state variable has been updated, I am well-versed in its functionality. I'm currently drafting this post on my phone while away from home. Here's the setup I have: const [dateValue ...

Send a collection of objects by submitting a form

I have a component with the following html code. I am attempting to dynamically generate a form based on the number of selected elements, which can range from 0 to N. <form #form="ngForm" id="formGroupExampleInput"> <div class="col-xs-5 col-md- ...

What is the importance of using ChangeDetectorRef.detectChanges() in Angular when integrating with Stripe?

Currently learning about integrating stripe elements with Angular and I'm intrigued by the use of the onChange method that calls detectChanges() at the end. The onChange function acts as an event listener for the stripe card, checking for errors upon ...

Strategies for capturing POST data sent to a JavaScript webpage

The request is sent from an external source beyond my control xyz.php <form action='https_:_//xyz.com/javascriptFile' method='POST'> <input type='text' name='data' /> </form> to: (My custom f ...

Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript. But what about accepting any number of objects as parameters in a function? This is my current implementation: function merge<T>(objA: T, objB: T){ return Object. ...

Issue: Issue:0308010C:unsupported function in digital envelope methods- Next.js

If you're facing this issue in your Next.js project with Node version 17, I've tried several solutions and found the most effective one. Here's how you can resolve this problem if it occurs for you: > <a href="/cdn-cgi/l/email-protec ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

Encountering an issue with Apollo subscriptions in Next.js, where an Observable is being cancelled prematurely with an error message

While working on my Next.js project, I encountered an issue with implementing apollo/graphql subscription. My graphql server is located in an external Next.js service and I have successfully worked with queries and mutations. However, when trying to use th ...

Error: Unable to locate module: 'fs' - NextJS

Currently, I am working on integrating node-jsencrypt with NextJS (tsx): index.tsx import JSEncrypt from 'node-jsencrypt'; package.json "node-jsencrypt": "^1.0.0" Log error - ./node_modules/node-jsencrypt/index.js:2:0 Modu ...

The Recoil Nexus encountered an error: the element type provided is not valid. It should be a string for built-in components or a class/function for composite components, but an object was

Encountered the following error message: Error - Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. at ReactDOMServerRenderer.render ... This issue arose when integra ...

When attempting to create, an error occurs: Uncaught TypeError: Unable to access properties of undefined (retrieving 'id')

In the process of creating a public prayer journal that allows users to include their favorite Bible verses, I encountered an issue while trying to add a prayer or verse. The error message "caught (in promise) TypeError: Cannot read properties of undefined ...