Having trouble locating a module while utilizing custom import paths in multiple tsconfigs

My current project involves the use of multiple tsconfig.json files. I'm aiming to streamline all imports, but oddly enough, shortened imports aren't functioning correctly in a specific situation.

Here's how my project is structured:

foo/
|  main.ts
|  tsconfig.json
projects/
|  bar/
|    index.ts
tsconfig.json

Every time I try to compile foo/main.ts, I encounter this error: Cannot find module @bar/shared.

Here are some key points:

The file projects/bar/index.ts merely exports a basic class: export class Foo {}

Within foo/main.ts, I attempt to import the Foo class like so:

import {Foo} from '@bar/shared';

Lastly, the tsconfig.json located within the foo directory:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true,
    "lib": ["es6", "dom"],
    "types": [
      "node"
    ],
    "outDir": "../dist/foo"
  }
}

And the main root tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "@bar/shared": ["projects/bar"]
    }
  }
}

My IDE shows no issues, but unfortunately, I am unable to successfully compile.

Answer №1

Short Answer

To resolve the issue, remove the baseUrl entry from your foo/tsconfig.json file which is conflicting with the one in the root tsconfig.json file.

Additional Information

The baseUrl specifies the base directory for resolving module names and mapping paths. In this case, when trying to resolve the @bar/shared path mapping, it searched relative to the baseUrl of ./src. Since ./src is a relative path based on the location of the /foo/tsconfig.json file, the resolved path was ./foo/src/projects/bar/.

You can find more information on module resolution in the module resolution docs.

--traceResolution

For troubleshooting these errors, you can use the --traceResolution option while building. Building from the foo/ directory will provide output like:

Loading module as file / folder, candidate module location

'C:/dev/temp/foo/src/projects/bar'
, target file type 'TypeScript'.

Runtime Configuration

Note that TypeScript path mappings do not rewrite paths at runtime. If using node, ensure it knows how to locate @bar/shared by configuring path mappings in the runtime environment. You can use a package like https://www.npmjs.com/package/module-alias for this purpose.

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

Sort the array based on the enum name rather than its value

Below is an example of an enumeration: export enum Foo { AA = 0, ZZ = 1, AB = 2, ER = 5 } In my case, I want to sort my Bars based on the name of the enum (AA, AB, ER, ZZ), rather than the numerical value (0, 1, 2, 5) that they represent. ...

Setting the desired configuration for launching an Aurelia application

After creating a new Aurelia Typescript application using the au new command from the Aurelia CLI, I noticed that there is a config directory at the root of the project. Inside this directory, there are two files: environment.json and environment.productio ...

Tips for handling race conditions in useEffects when a component may potentially unmount at any given moment in React

Currently using TypeScript 4 and React 17. Imagine having the following component: This component is part of a React Navigation conditional stack navigator. When the user logs out, the component gets automatically unmounted along with the UI, displaying ...

The initialization function is not being invoked

I've set up a new project using vue ui with typescript, babel, and a linter. Everything seems to be working smoothly, except I'm running into some confusion with implementing the Composition API's setup method. For some reason, it doesn&apos ...

typescript react interface for managing state and properties

As I delve into a project utilizing TypeScript and React, two technologies that are new to me, I find myself pondering the use of interfaces in TypeScript and how they connect to props and states. It seems crucial for my application to function properly th ...

Debugger for Visual Code unable to locate URL in Microsoft Office Add-in

I recently installed the Microsoft Office Add-in Debugger VS code extension, but I'm having trouble getting it to work despite following the instructions. Every time I try, an error message pops up: https://i.sstatic.net/h2FYs.png Upon inspecting my ...

When utilizing multer to manage POST requests with form data, req.body appears as [Object: null prototype] {} while req.files remains unpopulated

Trying to send form data via Postman to an express server on Firebase functions. Below is the code for receiving the POST request: import * as functions from 'firebase-functions'; import express = require('express'); import multer = req ...

Angular is not able to access the value of a promise in a different function after it has been retrieved

I have a form with default values that should be added to the form fields when it appears. There are two functions: #1 for fetching data from the backend and #2 for displaying the form: person$: any; ngOnInit() { this.getPersonData(123) this.buildPer ...

Can the return type of a function be determined dynamically at runtime by analyzing a function parameter value?

Let's delve into this concept with an illustrative example! interface Query { foo: any; } interface Mutation { bar: any; } type OperationName = keyof Query | keyof Mutation; const request = async <T>(args, operationName: OperationName): P ...

Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document. The function is executed in a loop up to a value of 5. However, even though the function runs 5 times, the value of 'i' always reflects the last value. The ...

Typescript error: The argument containing 'username' and 'password' fields cannot be assigned to a parameter expecting only a 'string' type

My service is designed to take an endpoint and execute a HTTP call. Here is the code snippet: export const updatePassword = (data: { username: string; password: string; }): HttpResponse<string> => { const { usernam ...

I am struggling to comprehend the data organization illustrated by the typescript type declaration

type DocumentData = { [field: string]: any }; let data1: DocumentData = {4:3}; console.log(data1); //{4:3} It appears that the DocumentData type in the code above defines an object type where the key is of string type and the value can be of any type. Th ...

What causes my TypeScript to occasionally return an instance and other times return a class?

I've been developing an app to enhance my understanding of TypeScript. It functions perfectly in Chrome, however, I encounter a problem when running it in Edge. The issue lies within this method: set position(pos: Point) { const diffAsPoint ...

What is preventing Typescript from utilizing the includes function for arrays?

I understand that Typescript is based on ES6 or ES2015. However, I'm confused because anArray.includes('ifExist'); is only available in ES6. Even though I'm using Typescript, why am I unable to use it? The error message says that anAr ...

Ways to "Compile out" log commands

In my typescript project, there is a section of code dedicated to creating debug information. However, upon profiling the application, I discovered that this debug code is causing a significant performance impact. Currently, my approach involves setting a ...

Issue with TypeORM: The database table is not being created during migration execution in the SQLITE environment

I'm currently encountering an issue with utilizing migrations in TypeORM with a sqlite3 database. My goal is to achieve consistency across different environments (local/testing/staging/production) by only using runtime environment variables that will ...

Error encountered: Dev server does not have an interface defined

I recently utilized the react-ts template to create a project with vite v5. However, when I run the application using pnpm dev, an error message pops up: App.tsx:9 Uncaught ReferenceError: CharacterConnectionStatus is not defined at App.tsx:9:22 Look ...

Maintaining type information while iterating over an object with Typescript

I am faced with the challenge of wrapping functions within an object in order to use their return values, all without altering their signature or losing type information. // An object containing various functions const functions = { foo, bar, baz } // Exa ...

What could be causing the code to not wait for the listener to finish its execution?

I've been attempting to make sure that the listener has processed all messages before proceeding with console.log("Done") using await, but it doesn't seem to be working. What could I possibly be overlooking? const f = async (leftPaneRow ...

Unable to find the 'Restore Packages' option when right-clicking on package.json in Visual Studio 2015 update3

Currently embarking on my Angular 5 journey with Visual Studio 2015 (Update 3), I encountered an issue where the "restore packages" option is missing when right-clicking on the 'packages.json' file. Any advice on how to proceed? ...