Having encountered the same challenge, I decided to create a library and utilize it across multiple projects. The first step is to ensure that your library is included in the main tsconfig.json file under the paths property.
"paths": {
"@projectName/LibraryName1": ["libs/LibraryName1/src/index.ts"],
"@projectName/LibraryName2": ["libs/LibraryName2/src/index.ts"],
....
}
Next, you need to add your project to the main angular.json file.
"projects": {
"LibraryName1": {
"root": "libs/LibraryName1",
"sourceRoot": "libs/LibraryName1/src",
"projectType": "library",
"prefix": "projectName",
"projectType": "library"
...
}
}
Make sure to review the tsconfig.json file for the specific app where you intend to use the library. It's crucial to remove the paths property as it has already been added to the main tsconfig.json (in my case, I utilized nrwl for managing multiple apps).
Now, you should be able to reference any of your library projects like this:
import { class1, class2 } from '@projectName/libraryName1';
Don't forget to export your classes (assuming you have a models library) using the index.ts file:
export * from './lib/class1';
export * from './lib/class2';
If you have a UI library with components, create a module, add the components to it, and then export it using the index.ts file. The module file should be located in the lib folder. For example:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NumberOnlyDirective } from './directives/number-only.directive';
@NgModule({
imports: [CommonModule],
declarations: [NumberOnlyDirective],
exports: [NumberOnlyDirective]
})
export class UiModule {}
index.ts file for the UI library:
export * from './lib/ui.module';
Include the reference to the UI module in your project's app.module.ts file:
import { UiModule } from '@projectName/LibraryName1';
Ensure to include it in the imports section as well:
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
NgxPaginationModule,
Ng2OrderModule,
Ng2SearchPipeModule,
AngularEditorModule,
RichTextEditorAllModule,
NgxPrintModule,
DevExpressModule,
UiModule
...
],