PrivateJoker
PrivateJoker

Reputation: 791

Angular Library - 'rootDir' is expected to contain all source files. (environment.ts)

I was working on my first Angular 7 library, however I am getting the this error when trying to compile the library.

Error: error TS6059: File '...environment.ts' is not under 'rootDir' 'my-angular-library\projects\my-library\src'. 'rootDir' is expected to contain all source files.

Looking at my tree I have:

-projects
  -my-library
     -src
-src
  - environments

In my class I have the following import:

import { environment } from "src/environments/environment";

I was checking other threads where they mentioned bugs in typescript, however I am running the latest version "typescript": "~3.1.1".

Other threads mentioned about a misconfigured rootDir. I checked my project and I do not have rootDir defined in any of the config files.

I don't need to add an environment to the projects do I?

Upvotes: 5

Views: 7240

Answers (1)

peinearydevelopment
peinearydevelopment

Reputation: 11474

All files referenced by the library need to be contained within project\my-library\src directory(or pulled in from another module) in order for the library to build properly.

I don't think you would want to include an environment file directly in your library either. During the build of the application, that environment file would be switched out in the application. With a library though, you build it and then import it into your application already built, so that file won't be switched out appropriately.

The best solution I'm aware of is to create a Token in your library and export that from the api of the library. Then in the application using the library, you would provide the environment through the DI container utilizing that token.

For example, in your library, you would do something like the following:

project\my-library\src\lib\environment-token.ts

import { InjectionToken } from '@angular/core';

export let ENVIRONMENT_TOKEN = new InjectionToken('environment');

project\my-library\src\public_api.ts

export * from './lib/environment-token.ts'

project\my-library\src\lib\component.ts

import {
  Component,
  Inject
} from '@angular/core';

import {
  ENVIRONMENT_TOKEN
} from './environment-token';

@Component({
  selector: 'aa-component',
  template: `
})
export class Component {
  constructor(@Inject(ENVIRONMENT_TOKEN) private environment: any) {
  }
}

And then in your application, you would do something like the following:

import {
  NgModule
} from '@angular/core';

import {
  YOUR_MODULE,
  ENVIRONMENT_TOKEN
} from 'YOUR_LIB_NAME';

import {
  environment
} from './environments/environment';

import {
  AppComponent
} from './app.component.ts'

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    YOUR_MODULE
  providers: [
    { provide: ENVIRONMENT_TOKEN, useFactory: () => environment }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Upvotes: 2

Related Questions