The error message "The file 'environment.ts' is not located within the specified 'rootDir' directory" was encountered during the Angular Library build process

When attempting to access the environment variable in an Angular 9 library, I encountered an error during the library build process.

Here is how it was implemented:

import { EnvironmentViewModel } from 'projects/falcon-core/src/lib/view-models/environment-view-model';

class EnvironmentImpl implements EnvironmentViewModel {
  production = false;
  openID = {
    authority: "https://dev-816623.okta.com/oauth2/XXXXXXXXXXXXX",
    client_id: "XXXXXXXXXXXXX",
    redirect_uri: "https://localhost:4200/auth-callback",
    post_logout_redirect_uri: "https://localhost:4200",
    response_type: "code",
    scope : "openid profile email"
  }
}

export const environment = new EnvironmentImpl();

View Model

export abstract class EnvironmentViewModel {
    abstract readonly production: boolean;
    abstract readonly openID: IOpenIdViewModel;
}

export declare interface IOpenIdViewModel {
    authority?: string;
    client_id?: string;
    redirect_uri?: string;
    response_type?: string;
    scope?: string;
    silent_redirect_uri?: string;
    post_logout_redirect_uri?: string;
    filterProtocolClaims?: boolean
    loadUserInfo?: boolean
    automaticSilentRenew?: boolean;
    monitorSession?: boolean;
    accessTokenExpiringNotificationTime?: number;
    checkSessionInterval?: number;
    silentRequestTimeout?: number;
}

In the Module

import { environment } from 'src/environments/environment';
 providers: [
    { provide: EnvironmentViewModel, useValue: environment }
  ]

tsconfig.lib.json

   {
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/lib",
    "target": "es2015",
    "declaration": true,
    "inlineSources": true,
    "types": [],
    "lib": [
      "dom",
      "es2018"
    ]
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "strictMetadataEmit": true,
    "enableResourceInlining": true
  },
  "includes": ["../../src/environments/environment.ts"],
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ]
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "@falcon/core": [
        "dist/@falcon-ng/core"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

The error message persists as:

ERROR: projects/falcon-core/src/lib/falcon-core.module.ts:28:29 - error TS6059: File '/Users/macbook/Projects/project-falcon/src/environments/environment.ts' is not under 'rootDir' '/Users/macbook/Projects/project-falcon/projects/falcon-core/src'. 'rootDir' is expected to contain all source files.

28 import { environment } from 'src/environments/environment';

For more information, refer to https://github.com/nrwl/nx/issues/208

Answer №1

Discovered a more effective solution

Utilizing Library Modules

export class FalconCoreModule {
    public static forRoot(environment: any): ModuleWithProviders {
      return {
        ngModule: FalconCoreModule,
        providers: [{ provide: EnvironmentViewModel, useValue: environment }]
      };
    }
}

Now, the project that uses this library can pass the environment variable as the root element.

import {environment} from "../environments/environment";
@NgModule({
            declarations: [],
            imports:[
                FalconCoreModule.forRoot(environment)
            ],
            bootstrap: [AppComponent]
        })

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 can you merge arrays in Angular based on their unique names?

Is there a way to combine objects within the same array in Angular based on their names? [{ "name":"Navin", "id":"1" }, { "name":"Navin", "mark1":"98" ...

Guide on implementing findOne for name validation in Node.js using data from MongoDB

Can someone help solve the issue of name duplication and provide guidance on how to execute the codes in Postman API? The attached codes can be found below: *employeemodel.js enter image description here *employeecontroller.js enter image description her ...

Should the checkbox be marked, set to 1?

I am looking for a way to call a method when the user checks or unchecks multiple checkboxes. Do you have any suggestions on how I can achieve this? Here is what I have tried so far: <input type="checkbox" [ngModel]="checked == 1 ? true : checked == 0 ...

The request to DELETE the employee on the server at http://localhost:3000/employees/$%7Bid%7D could not be processed because it was not found

removeEmployee(id: number): Observable<any> { return this._http.delete('http://localhost:3000/staff/${id}'); } } error:HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:30 ...

Testing Angular Service Calls API in constructor using Jasmine Test

My service is designed as a singleton, and its constructor initiates an API call function. This simplifies the process during service initialization, reducing the complexity and dependencies on various components like AppComponent to import and execute API ...

The Angular application encountered errors while trying to resolve main.ts, polyfile.test, and style.css

I encountered an issue while trying to run my Angular app in a Docker container. Here are the steps I followed: 1) Installed npm (v.3.5.2), node (v. 12.15.0), and angular CLI (v. 9.0.1) on my local machine 2) Created an Angular project locally using the ...

Unleash the potential of a never-ending expansion for grid cells on Canvas

ts: templateStyle = { display: 'grid', 'grid-template-columns': 'calc(25%-10px) calc(25%-10px) calc(25%-10px) calc(25%-10px)', 'grid-template-rows': '150px auto auto', 'grid-gap ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

Executing a component method from a service class in Angular

When trying to call a component method from a service class, an error is encountered: 'ERROR TypeError: Cannot read property 'test' of undefined'. Although similar issues have been researched, the explanations mostly focus on component- ...

Why is there a false positive in the onChange event for the number type in React TypeScript?

I encountered an error on line 24 Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345) This issue occurred while working with TypeScript for a React experiment. const App: React.FC = () => ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

Confirm that the dependency has been invoked using Sinon

I am currently working on testing whether a dependency has been called or not. Here is an example of my code: export default class vehicle { private builder: CarBuilder; constructor() { this.builder = CreateCar(); <- factory return fake data } crea ...

Is it possible to integrate @google-cloud/logging into an Ionic4/Angular8/Firebase client application? Tips for resolving module import issues

I am trying to implement nodejs-logging in my app using Ionic 4, Angular 8, and Firebase for writing logs to StackDriver. In the root of my app, I have taken the following steps: Installed @google-cloud/logging using npm Navigated to @google-cloud/loggi ...

Cypress: Unable to properly stub API with cy.intercept()

Whenever I utilize the cy.intercept() function, the API fails to stub. cy.intercept("GET", `${API}farm/list`, { body: { statusCode: 200, message: "Request successful", result: seededFarmList, }, }); The way I import the fixture file is as ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

Angular - Detecting Scroll Events on Page Scrolling Only

I am currently working on implementing a "show more" feature and need to monitor the scroll event for this purpose. The code I am using is: window.addEventListener('scroll', this.scroll, true); Here is the scroll function: scroll = (event: any) ...

"Fixing the cubic-bezier for the exiting animation ends up causing issues with the entering

Trying to implement a collapsing list animation using React/Joy-UI. Below is the Transition element code snippet: <Transition nodeRef={nodeRef} in={browseOpen} timeout={1000}> {(state: string) => (<List aria-labelledby="nav-list-bro ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...

Angular 14 captures typed form data as `<any>` instead of the actual data types

On the latest version of Angular (version 14), I'm experiencing issues with strictly typed reactive forms that are not functioning as expected. The form initialization takes place within the ngOnInit using the injected FormBuilder. public form!: For ...

The message "Expected a string literal for Angular 7 environment variables" is

I'm currently working on setting up different paths for staging and production environments in my Angular project, following the documentation provided here. I have a relative path that works perfectly fine when hardcoded like this: import json_data f ...