Angular CLI provides a command-line interface to do a lot of things like linting, changing configuration of your application, view docs, run and build your app etc etc..
Out of these commands, there is a generate command which allows us to create building blocks of our application. In this article, we are going to learn how to generate library and watch for changes in the library in an angular application.
ng new my-lib-app –createApplication false
This command will create angular application with an empty workspace.
Go to the root of this project and generate a library.
cd my-lib-app ng g library lib1
This command will generate a library project for you. Now build this library:-
ng build lib1
Depending on angular.json configuration, it will generate build files in the output path. By default it should be dist/lib1.
Link this library in your local system. Go to the build folder of your library and run command:
It will globally link your library in your local system and you will be able to install it in any app in your system.
Run following command to create an angular app:
ng g application myapp
Now install library which we've created earlier. But to enable watching, we’ll have to install this library with a file system url:
npm install file:./dist/lib1
Now run following commands:-
ng build lib1 --watch ng serve
Now use any component from your library in the app. Run it. Make some changes to the library and you’ll see that app is updating automatically based on those changes.
You can find complete source code of this article here:-
This project was generated with Angular CLI version 9.0.2.
ng serve for a dev server. Navigate to
http://localhost:4200/. The app will automatically reload if you change any of the source files.
ng generate component component-name to generate a new component. You can also use
ng generate directive|pipe|service|class|guard|interface|enum|module.
ng build to build the project. The build artifacts will be stored in the
dist/ directory. Use the
--prod flag for a production build.
Running unit tests
ng test to execute the unit tests via Karma.
Running end-to-end tests
ng e2e to execute the end-to-end tests via Protractor.
To get more help on the Angular CLI use
ng help or go check out the Angular CLI README.