Creating Shared Libraries in Angular Monorepo
Demonstrating the creation of a shared utility library within an Angular monorepo setup, and how to use it across different applications.
ng generate library shared-utils --prefix=utils
Create a shared utility library named 'shared-utils' within an Angular workspace with 'ng generate library' command. The '--prefix' option sets the prefix to 'utils' for components, directives, and pipes within the library.
export class StringUtils {
static capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
In the 'shared-utils' library, create a utility class, here named 'StringUtils', with a static method 'capitalize' that capitalizes the first letter of a string.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { StringUtils } from './string-utils';
@NgModule({
declarations: [],
imports: [
CommonModule
],
exports: [StringUtils]
})
export class SharedUtilsModule {}
Create a module file for the 'shared-utils' library, import the 'StringUtils' class, and export it within the '@NgModule' so it can be imported by other modules in the monorepo.
import { SharedUtilsModule } from 'shared-utils';
@NgModule({
imports: [
// other imports...
SharedUtilsModule
],
// other module properties
})
export class AppModule {}
In an Angular application within the monorepo, import the 'SharedUtilsModule' from the 'shared-utils' library into the application's root module, here named 'AppModule'.
import { StringUtils } from 'shared-utils';
@Component({
selector: 'app-example',
template: '{{ title | capitalize }}'
})
export class ExampleComponent {
title = 'example';
ngOnInit() {
this.title = StringUtils.capitalize(this.title);
}
}
Usage of 'StringUtils' class in a component within the application. The 'capitalize' method is called in the 'ngOnInit' lifecycle hook to transform the 'title' property.