Creating own libraries for Angular with Nx
npx create-nx-workspace@latest library-app --preset angular-monorepo
- Library generator
- Library schema
- Important switches:
- --name: name of the library
- --directory: directory of the library
- --style: style of the library
- --skipTsConfig: skip tsconfig
- --skipFormat: skip prettier
- --unitTestRunner: unit test runner
- --linter: linter
- --publishable: possibility to publish on npm
- --buildable: incremental build
- --importPath: import path
- Generate your library:
npx nx g @nx/angular:library ngc-form-controls --publishable --buildable --import-path=@cherryapp/form-controls
- Install Bootstrap and Font-awesome packages:
npm i -D bootstrap font-awesome cd ngc-form-controls- Add packages to the package.json's peerDependencies (it is needed for production):
"peerDependencies": {
"bootstrap": "^5.2.0",
"font-awesome": "^4.7.0"
},- Also add packages to the devDependencies of the parent project (only for development):
"devDependencies": {
"bootstrap": "^5.2.0",
"font-awesome": "^4.7.0"
},- Import Bootstrap into the CSS:
npx nx run library-app:serve- Save it into the start script in the package.json file!
- The path of the library from the tsconfig.base.json:
@cherryapp/form-controls- Import the component from the path:
import { NgcFormControlsComponent } from '@cherryapp/form-controls';
// ...
imports: [
// ...
NgcFormControlsComponent,
],- Place the component in the template:
<div>
<lib-ngc-form-controls></lib-ngc-form-controls>
</div>cd .\ngc-form-controlsnpx nx g @nx/angular:component rating- Choose the right path.
- Import the new component into the app component and display it.
- Publish assets into the package, in the ng-package.json file:
{
"assets": [
{
"input": "src/assets",
"glob": "**/*",
"output": "assets"
}
]
}- ONLY FOR DEVELOPMENT, place the following settings the parent's project.json:
"assets": [
"apps/library-app/src/favicon.ico",
"apps/library-app/src/assets",
{
"glob": "**/*",
"input": "ngc-form-controls/src/assets",
"output": "assets"
}
],npx nx run ngc-form-controls:build --prod- When we build the entire application, the library also will be built:
npx nx run library-app:build --prod
- Article
npm loginnpm addusernpx nx run ngc-form-controls:build --prodcd dist/ngc-form-controlsnpm publish --access=public
- Create a new Angular application
npm i ngc-form-controls- Import the desired component:
import { CountrySelectorComponent } from 'ngc-form-controls';- Include it into the template:
<div class="form-group">
<label for="name">Country</label>
<ngc-country-selector formControlName="country"></ngc-country-selector>
</div>- Unit testing of the library:
npx nx run icell-form-controls:test- E2E testing of the parent application:
npx nx run library-app-e2e:e2e