Angular Monorepo Patterns with Nx — Part2 — Organizing Code With Libraries

Laakissi Achraf
3 min readMay 17, 2020

Why Use Angular Libraries?

You should use Angular libraries because sharing code across one app is easy, but sharing code between different projects requires extra steps.

When we do encounter services or components that can be reused across different teams and projects, and that ideally do not change very often, we may want to build an Angular Library.

Types Of Nx Libraries

With Nx, we can partition our code into small libraries with well-defined public API. So we can categorize our libraries based on what they contain.

These are some common library types:
Feature libraries: Developers should consider feature libraries as libraries that implement smart UI (with injected services) for specific business use cases or pages in an application.

UI libraries: A UI library contains only presentational components.

Data-access libraries: A data-access library contains services and utilities for interacting with a back-end system. It also includes all the code related to State management.

Utility libraries: A utility library contains common utilities and services used by many libraries and applications.

Creating a library using Nx

Nx allows us to add a library in the monorepo, which can be used by multiple applications and also published as a reusable library to the package manager.

Let us generate a UI library to make the header shared with all applications of our project.

ng generate lib ui-header — directory=shared — tags=scope:shared,type:feature

Scope relates to a logical grouping, business use-case, or domain.

Type relates to the contents of the library and indicates its purpose and usage. Examples of types are ui, data-access, and feature.

Content of shared-ui-header.module.ts
Content of shared-ui-header.component.ts

I added some html content to the shared-ui-header.component.html file,now let’s shared with our app.

app.module.ts

import { SharedUiHeaderModule } from ‘@myworkspace-nx/shared/ui-header’;

imports: [ … , SharedUiHeaderModule,…. ]

app.module.html

our header is shared with our app.

Libraries offer a way to modularize code and to make it easy to share code across applications in the workspace. they also can be classified with scope, type, platform and other classifiers to organize them.

--

--