The interpretation of path mapping in tsconfig as an external module is essential for maintaining code organization

(note: running Angular 8 and Node version 12.15.0)

UPDATE: It appears to be a bug, so I have opened an issue here

I'm in the process of developing a library where I have defined the path @env in the tsconfig.json:

{
  "compilerOptions": {
    [...]
    "paths": {
      "@env/*": [
        "projects/mylib/src/environments/*"
      ]
    }
}

In my code, I reference the environment like this:

import { environment } from '@env/environment';

However, it seems that the compiler is getting confused because when I try to build using (ng build my-lib), I receive the following warning message:

WARNING: No name was provided for external module '@env/environment' in output.globals – guessing 'environment'

Furthermore, importing the module into a project results in this compilation error:

ERROR in The target entry-point "my-lib" has missing dependencies:
 - @env/environment

It seems like @env/environment is being treated as an external module. How can I resolve this issue?

Steps to reproduce:

Note: I have created a ready-to-use SSCCE available here

  1. Create a new project (ng new acme) with basic options: no routing, plain CSS styling.
  2. Within the project, create a library (ng g generate library my-lib)
  3. Under projects/my-lib/src, create a folder environments containing 2 files: environment.ts and environments.prod.ts
  4. Configure
    projects/my-lib/tsconfig.lib.json
    by adding the block as shown below:
{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/lib",
    "target": "es2015",
    "declaration": true,
    "inlineSources": true,
    "types": [],
    "lib": [
      "dom",
      "es2018"
    ],
    "paths": {
      "baseUrl": [ "./" ],
      "@env/*": [ "projects/my-lib/src/environments/*" ]
    }
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "strictMetadataEmit": true,
    "enableResourceInlining": true
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ],
}

Your project structure should resemble the following:

.
├── angular.json
├── browserslist
├── e2e
│   ├── protractor.conf.js
│   ├── src
│   │   ├── app.e2e-spec.ts
│   │   └── app.po.ts
│   └── tsconfig.json
├── karma.conf.js
├── package.json
├── package-lock.json
├── projects
│   └── my-lib
│       ├── karma.conf.js
│       ├── ng-package.json
│       ├── package.json
│       ├── README.md
│       ├── src
│       │   ├── environments
│       │   │   ├── environment.prod.ts
│       │   │   └── environment.ts
│       │   ├── lib
│       │   │   ├── my-lib.component.spec.ts
│       │   │   ├── my-lib.component.ts
│       │   │   ├── my-lib.module.ts
│       │   │   ├── my-lib.service.spec.ts
│       │   │   └── my-lib.service.ts
│       │   ├── public-api.ts
│       │   └── test.ts
│       ├── tsconfig.lib.json
│       ├── tsconfig.lib.prod.json
│       ├── tsconfig.spec.json
│       └── tslint.json
├── README.md
├── src
│   ├── app
│   │   ├── app.component.css
│   │   ├── app.component.html
│   │   ├── app.component.spec.ts
│   │   ├── app.component.ts
│   │   └── app.module.ts
│   ├── assets
│   ├── environments
│   │   ├── environment.prod.ts
│   │   └── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── polyfills.ts
│   ├── styles.css
│   └── test.ts
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.spec.json
└── tslint.json

Now,

  • To reproduce the warning, build the library: ng build my-lib
  • To reproduce the error, import MyLibModule into the main project and build it: ng build

Answer №1

The angular maintainers provided this insight in response :

According to them, using path mappings for libraries is not recommended.

In addition, they stated:

It has never been supported to use path mappings in a library, and it appears that in your case, they only worked due to ts configuration issues leaking from the library to your application.

The bottom line is: AVOID incorporating path mappings in libraries.

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

How to fix the error: ui-switch is not a recognized element in Angular 5?

Currently, I am attempting to utilize the ui-switch feature mentioned in this link. However, I have encountered an error: ng : ui-switch is not a known element ng : if ui-switch is An angular component then verify it's a part of this module ...

Can Typescript union be utilized to define field choices?

I am working with a type that can accept either a string or a number as options, defined like this: type Result = string | number type ValueData = { data: Result } const valueDataSchema = new mongoose.Schema({ data: { type: Result } ...

Sending an email using Angular is a straightforward process that involves utilizing the built

I need help figuring out how to code a function in Angular or TypeScript that will open Gmail when a specific email address is clicked. I've tried different methods but haven't been successful so far. ...

Why has the need to import toPromise in Angular/rxjs vanished?

Many responses on Stack Overflow mention that to prevent issues like Error message: Property 'toPromise' does not exist on type 'Observable' in Angular, you are advised to import 'rxjs/add/operator/toPromise'. I followed t ...

Receiving API response with a format similar to JSON, but encountering an issue during the parsing process

My API is returning the following: {"permissions": [{"id":1,"product_id":10,"permission_type":"ADD","name":"Add"}, {"id":2,"product_id":10,"p ...

Issue with Angular2: The [routerLinkActive] directive does not update when using _router.navigate

My app includes several routerLinks that I have styled using [routerLinkActive]="['active']". Everything works perfectly when I click on one of the routerLinks to navigate. However, when I try to navigate using: this._router.navigate( [ thisUrl ...

Typescript Key-Value Pair Dynamic Typing

Can someone please assist me with this task? Here is the API response I received: Week At A Glance: { objA: [{}], objB: [{}] }, records: { Employee Records: [{}], Email Records: [{}], message: "" }, history: { [{}] } Despite my attempts, I am facing dif ...

Incorporate a dynamic HTML attribute into the ChildComponent

I am looking to include a dynamic HTML property called 'hits' in my ChildComponent within the HTML code: <child-component test={{ variable }}></child.component> I do not intend to use it as an input, but rather just for testing p ...

How come a Google Maps API component functions properly even without using *NgIf, but fails to work when excluded in Angular 9?

I recently followed the guide provided in this discussion with success. The method outlined worked perfectly for loading search boxes using this component: map.component.html <input id= 'box2' *ngIf="boxReady" class="controls" type="text" p ...

The text geometry remains consistent despite adjustments to the height and size parameters

I am facing a unique issue with text loading in my react three fiber project. The text does render, but it remains extremely small and unreadable, even though I can see a tiny pixel of the text color in the correct position. Strangely, I have not been able ...

Angular signal failed to update after the next render cycle

When utilizing angular SSR, why is it necessary to manually initiate a change detection when using afterNextRender? Considering this is an angular API. Is there a workaround for this issue? afterNextRender(() => { this.someAPI.then( ...

There is an issue with the Hook call on the component list map in ReactJS

While working on Review components, I encountered an error when trying to use hooks. Here is the issue: I am using YhSection to manage my parallel components and utilizing array map to incorporate them in the layout content. Interestingly, if I use hoo ...

Developing a dynamic object deserializer in TypeScript/Angular 2

My background is in C# where I have experience working in a dynamic and reflective manner. Now, I am transitioning to TypeScript for writing a class and trying to apply similar principles. To provide context, I am converting an existing application into a ...

There is no index signature in AxiosStatic

As I convert a hook from JavaScript to TypeScript, I encounter the following error: (alias) const axios: AxiosStatic import axios Element implicitly has an 'any' type because type 'AxiosStatic' has no index signature. Did you mean to ca ...

Subscribing to ngrx store triggers multiple emissions

Currently, I have an app with a ngrx store set up. I am experiencing an issue where, upon clicking a button, the function that fetches data from the store returns multiple copies of the data. Upon subsequent clicks, the number of returned copies grows expo ...

Creating a variable that is not defined and then converting it into

I have an issue with a function that returns an Observable. The problem is that when the function is called, the parameter works fine, but its value becomes undefined within the Observable. This is the function in question: import {Observable} from &apos ...

getting requestParam of type date from angular using spring

Hello everyone, I am new to working with Angular and Spring. I am attempting to send a GET request with some date parameters, but I keep encountering an error. Here is the HTML code snippet: <div class="form-row"> <div c ...

Typescript Error: TS2339: Unrecognized property 'map' on datatype 'string'

It appears that typescript does not currently support the new object types in ECMAScript 2015 (6th Edition, ECMA-262). Here is the code snippet I am working with: const SkipAny: string = requestBody.SkipAny; CurTester.SkipAny = SkipAny.map((value) => { ...

The request made for PUT calls in Asp Net Web Api 2.2 has resulted in a 400

Struggling to update my resource from Angular app with a Web Api call using PUT method. Despite trying Postman, all I get is a 400 Bad Request error. I have two questions: first, is the code correct considering web.config file and console output? And seco ...

The system encountered an error while trying to access the property 'enabled' of an undefined object

When working on a reactive form in my code, I need to ensure the values are properly set for the controls. ngDoCheck() { setControlValues(); } ngChanges(changes: SimpleChanges): void { setControlValues(); } private setControlValues() { try { ...