GUIDE: Creating an Angular library comprised of standalone feature sub-libraries

Currently in the process of developing a custom Angular library using Angular v 8.1.0, I am interested in figuring out how to organize it into different sub-libraries.

For instance, the Angular core is divided into separate parts like:

  • @angular/common
  • @angular/core
  • @angular/forms
  • and more.

Similarly, @angular/common has sub-directories that can be imported from:

  • @angular/common/http
  • @angular/common/locale
  • @angular/common/testing

I aim to implement a similar structure in my Angular library named cool-lib. I want different feature modules, such as common, featureA, and featureB, to remain independent of each other and have their own services/components, etc.

My goal is to achieve something like this:

import { CommonService } from 'cool-lib/common';
import { FeatAComponent, FeatAService } from 'cool-lib/feature-a';
import { FeatBModule } from 'cool-lib/feature-b';

Instead of:

import { 
  CommonService, 
  FeatAComponent, 
  FeatAService,
  FeatBModule
} from 'cool-lib';

It would also be beneficial to be able to update the version numbers of individual feature modules independently or have the flexibility to only install the necessary modules without installing the entire library (e.g., only needing featureA).

For example, in the package.json:

{
  "dependencies": {
    "cool-lib/common": "1.0.0",
    "cool-lib/feature-a": "1.0.0",
    "cool-lib/feature-b": "1.3.0"
  }
}

or simply:

{
  "dependencies": {
    "cool-lib/feature-a": "1.0.0"
  }
}

Instead of:

{
  "dependencies": {
    "cool-lib": "1.0.0"
  }
}

I have researched extensively on creating Angular libraries, but have not come across a solution for this specific scenario. Any guidance on this matter would be greatly appreciated!

Answer №1

In Angular, there is built-in support for multiple sub-libraries.

When you create a project, you start with the main "app" application, which is a typical Angular project. You can then add more sub-libraries to this structure, each being its own Angular Library project located in the library sub-folder.

A single Angular project can house numerous sub-library projects, each of which can be published individually as npm packages with their own package.json file.

npm allows for scoped package names, which means you can name a package like @angular/core, where @angular is the package's scope.

To add a scoped library to your Angular project, you can use the following command:

ng generate library @my-scope/my-library

When importing from a scoped project, make sure to prepend the scope to the package name. For example:

import { CommonService } from '@cool-lib/common';
import { FeatAComponent, FeatAService } from '@cool-lib/feature-a';
import { FeatBModule } from '@cool-lib/feature-b';

In the above code snippet, @cool-lib represents the scope, and common is the npm package name.

Scoped packages serve two main purposes:

  1. They prevent naming conflicts with other packages, for instance, @cool-lib/animations won't clash with @angular/animations.
  2. They help organize packages under node_modules/@cool-lib.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically obtaining the screen width in JSP using a variable

Could someone provide assistance on how to resize an image using an img src="blah.jpg?width=x" so that my page can be displayed at various sizes? I just need x (width) as a JSP variable. Update 2021: It's been 9 years since this question wa ...

Closing a modal using the Enter key in Angular 6

I was able to replicate the issue on StackBlitz using minimal code. To reproduce: Step 1: Input a word in the text field and press Enter on the keyboard. Step 2: A modal will pop up. Step 3: Hit Enter again on the keyboard. During Step 2, I encou ...

Encountering a hydration issue with an SVG element embedded within a Link component in Next

I'm encountering a hydration error related to an icon within a link, Here is the error message: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <svg ...

Exploring date comparisons in TypeScript and Angular 4

I'm currently working on a comparison of dates in typescript/angular 4. In my scenario, I've stored the system date in a variable called 'today' and the database date in a variable named 'dateToBeCheckOut'. My goal was to filt ...

Module `coc-tsserver` not found (error ts2307)

https://i.sstatic.net/k1MVW.png Working on a project using NeoVim with CoC for TypeScript development in a yarn-3 pnp-enabled environment. Suddenly, the editor stopped recognizing imports and started showing errors for non-existent modules (refer to the s ...

JavaScript not functioning properly for the Sibice challenge on Kattis

Currently, I am in the process of learning JavaScript and a friend recommended trying out Kattis for solving tasks, even though it might not be ideal for JS. As part of this challenge called Sibice, the goal is to determine if matches will fit into a box. ...

Submitting data to a PHP script using AJAX and the $_POST method

I'm attempting to transfer data from my AJAX request into a PHP $_POST variable in order to update my database. HTML <form id="23" method="post"> <select name="admin" onchange="chosenadmin(23)"> <option value="rick">rick&l ...

Prevent postback in case of validation error

In my current setup, I have a textbox control with the following specifications: <asp:TextBox ID="txtAmount" runat="server" AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]" On ...

Guide on displaying link parameter information on a separate webpage using only JavaScript

While doing some research, I came across an issue. I have a page called specifications.html with three links: details.html?id=1, details.html?id=2, and details.html?id=3. My goal is to display the details of each link when someone clicks on it. For examp ...

Using the Count() function in PHP to update information upon page refresh

I have created a basic cart that displays a div containing purchased items when hovered over. The issue I am facing is that every time I click on the add to cart button, it doesn't immediately update the number of items in the cart. I have to manually ...

Embracing Typescript version 2.7 and above allows for utilizing multiple types within a parameter, enabling developers to efficiently handle specific properties

Imagine a scenario where a ChildClass is extending the ParentClass. You can view the code on Stackblitz here. The ChildClass simply adds a public property called "brainPower": class ParentClass{ _me: string; constructor() { this._me = "I'm ...

Identify 404 errors in multi-file routes with Express

Recently, I've been diving into using Express and I'm facing some challenges with detecting 404 errors. In my main file app.js, I launch the server and specify different files to handle various requests. For instance: const app = express(); app ...

Eliminate items from a list that have duplicate properties

I have a collection of objects, each with a unique NAME property. However, there are duplicates in the collection where some objects share the same NAME. const arr = [ {name: "x", place: "a", age: "13" }, {name: "x", place: "b", age: "14" }, { ...

What is the best way to extract clean text from HTML using JavaScript?

I am struggling with the code below in my HTML file: function hideContent(){ // Need help with this part! } <input type="button" onclick="hideContent()" value="Hide Content"/> <p id='txt'> <span class="A">I am</span> ...

Error: The value "'827'" cannot be assigned to "Course_Content.course_outline_id" as it must be a valid instance of "Course_Outline"

While working on my django view, I encountered an error stating: ValueError: Cannot assign '827': 'Course_Content.course_outline_id' must be a 'Course_Outline' instance. I attempted to convert it to an int but it still didn&ap ...

Issue with button style in dropdown menu in Twitter Bootstrap

<nav class="nav-collapse user"> <div class="user-info pull-right"> <img src="http://placekitten.com/35/35" alt="User avatar"> <div class="btn-group"> ...

When outputting the $http response in the console, Angular displays null instead of the expected result,

I have encountered a peculiar issue with my local webservice developed using Spring. Everything seems to be functioning correctly when accessing it through the browser or Postman, but for some reason, when attempting a simple GET method with Angular/Ionic, ...

Displaying/Concealing specific choices using jQuery

Greetings! I am in need of some assistance with my coding query. I have been working on a piece of code where selecting 'x' should reveal another dropdown, which seems to be functioning correctly. However, if I navigate three dropdowns deep and t ...

Unable to locate and interact with a specific element within a dropdown menu while utilizing Protractor

I am currently facing an issue with selecting a checkbox from a dropdown in jq widgets. The code seems to work fine when the element is visible on the screen, but fails otherwise. I have tried various methods such as executeScript and scrollIntoView to bri ...

How can I take a screenshot from the client side and save it on the server side using PHP?

Currently, I am exploring the possibility of screen capturing at the client side. It appears that the "imagegrabscreen()" function can only capture screens on the server side. After some research, I discovered a new function that allows for screen capture ...