Search code examples
angulartypescriptangular-cli-v7

Angular project with external lib doesn't compile in AOT mode using angular-cli


I started a fresh new project, generated with angular-cli 8.1.2. I want to have a shared library for several microservices (apps). This library should NOT be included in the applications folder, it's a different project, has its own git. If I try that, the application does not compile in aot/production mode, but works in jit.

I want 2 projects in 2 directories for the application:

/test-lib
/test-app

So I first generate the lib with angular-cli:

ng new test-lib --create-application=false
(using defaults)
cd test-lib/
ng generate library test-lib --prefix=test
ng build test-lib

This generates the library folder and a project inside /test-lib/projects/test-lib

Now I generate the (first) application:

cd ..
ng new test-app
(using defaults)

Now I connect the lib to that app:

Adding "paths" to tsconfig.json:

"paths": {
  "test-lib": [
    "../test-lib/dist/test-lib"
  ],
  "test-lib/*": [
    "../test-lib/dist/test-lib/*"
  ]
}

Adding the import to app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { TestLibModule } from 'test-lib';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    TestLibModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And added this tag to app.component.html:

<test-test-lib></test-test-lib>

Running "ng serve" now works without problems.

Firing "ng build" in the folder test-app fails with:

ERROR in : Unexpected value 'TestLibModule in C:/Users/.../test-lib/dist/test-lib/test-lib.d.ts' imported by the module 'AppModule in C:/Users/.../test-app/src/app/app.module.ts'. Please add a @NgModule annotation.
enter code here

Additionally it reports:

: 'test-test-lib' is not a known element:
1. If 'test-test-lib' is an Angular component, then verify that it is part of this module.
2. If 'test-test-lib' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to 
the '@NgModule.schemas' of this component to suppress this message. ("
</ul>

[ERROR ->]<test-test-lib></test-test-lib>")

My tries to import the component in app.component.ts failed as well (not found)

Shouldn't it be possible to create a library with anglular-cli that lives in an external folder in a simple way?


Solution

  • You need to work with the public_api barrel in your library, import the module from it, then compile

    Also you can work with npm link to have separated directories