How to create angular library using Angular 12 - part 1
Step 1: Install angular cli
Install the CLI using the npm package manager.
npm install -g @angular/cli
Step 2: Create the workspace
Use the Angular CLI to generate a new workspace with the following commands.
ng new my-workspace --create-application=false --interactive=false
--create-application=false parameter avoids the creation of an initial application (default value is true). Otherwise, the Angular CLI creates an application in the src folder of the new workspace. It’s cleaner to generate all applications in the sub-folder projects of the workspace.
--interactive=false parameter is just here to avoid being prompted for useless parameter values such as whether the initial app (which we don’t generate) should include a routing module or what CSS preprocessor to use.
Once created the workspace, then change the directory by following command.
Step 3: Create a Library
ng generate library <library-name>command is used to generate library.
ng generate library my-lib
Step 4: Create an Application
ng generate application <application-name> command is used to generate application.
ng generate application my-app
To serve an application, run the following command.
ng serve --project=my-app
To build the library, run the following command.
ng build --project=my-lib
After build successful, we can get 2 paths.
Step 5: Implement library into application
Import the library module to app module.
After importing the module in app.module, Need to add the library component selector tag in app.component.html. We can find the selector tag in the file projects/my-lib/src/lib/my-lib.component.ts, where you can get selector inside @component decorator.
Step 6: Test Library in angular production environment
To build the production application use the following command.
ng build --project=my-app
After successful build, my-app folder will get created in dist folder.
To run the angular production build follow the below steps.
- Install the http-server globally.
npm install http-server -g
2. Run the angular production build.
To launch the angular production application in any of the above available URL’s.
In part 2 we will see about angular pipe’s