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

Issue with Unit Testing: "InterceptableStoreFactory" provider not found, even when it is included in the "providers" list

I'm currently in the process of writing unit tests for my Angular application using the TestBed approach. Specifically, I am focusing on testing components, so each spec file follows a similar structure: import... describe('AppComponent', ...

The array remains undefined even after being assigned within the subscribe function

I have encountered an issue in my Angular app where the array productLocations is being assigned in the ngOnInit method within a subscription, but it remains undefined when used in another method. Despite following advice on Stackoverflow to move the assig ...

How can I troubleshoot the issue of receiving 'undefined value' for property and event binding between various components in my Angular 7 application?

In my Angular application, I have three components: RecipeBook, RecipeList, and RecipeItem. The RecipeBook contains the RecipeList, which consists of 'n' recipe items. Additionally, there is a component called RecipeDetail that I want to display ...

A guide to dynamically display input fields according to the selected mat-radio button in Angular Material

I am currently utilizing angular material version 9.2.4 Within my project, I am implementing the angular material mat radio button with an input field. Each payment method will have its own corresponding input field. When the 'Cash' option is se ...

Set up the user django with standard configuration values

I'm currently working with Django and Angular 2, trying to create a user with default values, but it's not happening as expected... Model class Settings(models.Model): user = models.ForeignKey('auth.User', related_name='setti ...

Invoke an ActionCreator within a different ActionCreator

Calling an ActionCreator from another file is proving to be a challenge... The products.ts file contains the ActionCreators and Reducers for Products... import { setStock } from './Store.ts'; //.... export const addProduct = (product: IProduct) ...

Challenges with handling click events in Angular Material's mat-sidenav-content

When I add a click event to the mat-sidenav-content element like this: <mat-sidenav-content (click)="isNavBarOpened=false">, the mat-slide-toggle inside it stops functioning. Check out the code example here ...

Tips on how to dynamically uncheck and check the Nebular checkbox post-rendering

I incorporated a nebular theme checkbox into my Angular 8 App. <nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)">Enable</nb-checkbox> I am able to update the checkbox using the Boolean variable "enable_checked". Initia ...

Tips for sending parameters in Next.js without server-side rendering

I followed the documentation and tried to pass params as instructed here: https://nextjs.org/docs/routing/dynamic-routes However, I encountered a strange issue where the received params are not in string format. How is it possible for them to be in an arr ...

Submitting a form via NextJS to an internal API

After reading through the Next.JS documentation, I came across an interesting point. Note: Instead of using fetch() to call an API route in getStaticProps, it's recommended to directly import the logic from within your API route and make necessary cod ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

When trying to upload a file with ng-upload in Angular, the error 'TypeError: Cannot read properties of undefined (reading 'memes')' is encountered

Struggling with an issue for quite some time now. Attempting to upload an image using ng-upload in angular, successfully saving the file in the database, but encountering a 'Cannot read properties of undefined' error once the upload queue is comp ...

problem encountered when running "ionic cordova build android --prod --release"

A chat application has been developed using Ionic2. Upon attempting to generate a production build with ionic cordova build android --prod --release, the following error is encountered. Error: ./node_modules/rxjs/observable/BoundCallbackObservable.js ...

What is the best way to center align the placeholder in an ion-input field?

What is the best way to center align the placeholder in ion-input? Here's a screenshot of my current ionic input fields with left alignment. I've attempted to move the alignment to the center, but I've been unsuccessful. Can someone please ...

What is the best method for launching a Node.js (Express) app on a live server automatically?

My Angular app relies on an express backend. What is the best way to deploy this application on a remote server so that it always runs smoothly? ...

Using TypeScript to create a unique object type that is mapped with generics for each key

Suppose I have a type representing an array of two items: a list of parameters and a function with arguments corresponding to the parameters. I've created a handy function to infer the generic type for easy use. type MapParamsToFunction<A extends a ...

Angular firing a function in the then clause before the initial function is executed

I have a situation where I need to make multiple service calls simultaneously, but there is one call that must be completed before the others are triggered. I have set it up so that the other calls should only happen after the .then(function() {}) block of ...

What is the best approach to testing the React Hook "useEffect" that is used to make an API call with Typescript?

Currently, I am working on writing Jest-enzyme tests for a basic React application using Typescript along with the new React hooks. The main issue I am facing is with properly simulating the api call made within the useEffect hook. Within the useEffect, ...

The onChange function in React is not behaving as I anticipated

Consider the following data structure for tables: an array of objects containing nested objects: [ { "1": { "1": "Item s ", "2": "Manufacturer ", "3" ...

Building an Angular and NodeJS application with Mongoose pagination capabilities

I have a question regarding the design aspect of my project rather than delving into lots of code. My angular client interacts with a MongoDB collection through an HTTP call to a Node.js backend. I am looking to implement pagination for the results. To ach ...