Reputation: 255
Situation: I am quite new to Angular and want to create an Angular workspace with multiple applications and libraries. I followed this tutorial to create an Angular workspace with Nx in form of a MonoRepo. I created an app and a lib following the steps presented in the tutorial.
So I have an app called first-app and a lib called first-lib. In the first-lib I have a component first-lib-component. I want to use the component or best the library itself like this in my first-app.html:
<h2> This is my first-app </h2>
<first-lib></first-lib> OR
<first-lib-component></first-lib-component>
I have imported the first-lib in the app.module.ts and added the first-lib-module to the imports.
Problem: I want to use the created library within my created application and that's the point where I currently fail. I get an error stating "'first-lib-component' is not a known element".
The Nx website states that:
... the clients of the library are in the same repository, so no packaging and publishing step is required.
If no packaging is required, how can I use my shared components/projects (libraries)?
My question: How can I import and use the (component of the) library in the application?
Upvotes: 4
Views: 3325
Reputation: 35
The comment that says nx isn't useful could never be more wrong. Anyway, lets help you out now.
If you build multiple components, you will need to make a decision:
a) import all components every time you import the library:
// libs/first-lib/src/lib/first-lib.module.ts
@NgModule({
imports: [CommonModule, FirstLibComponent, SecondLibComponent],
exports: [FirstLibComponent, SecondLibComponent]
})
export class FirstLibModule {}
// libs/first-lib/src/index.ts
export * from ./lib/first-lib.module
// tsconfig.base.json
"paths": {
"@my-repo/first-lib": ["libs/first-lib/src/index.ts"],
}
// apps/app1/src/app/app.module.ts
import {FirstLibModule} from '@my-repo/first-lib'
b) import every component on its own
Assuming each of your components has an NgModule, the module files can simply be exported. Remember to remove the exports and imports that you placed in the FirstLibModule if you follow this route.
// libs/first-lib/src/lib/first-lib.module.ts
@NgModule({
imports: [CommonModule]
})
export class FirstLibModule {}
// libs/first-lib/src/index.ts
export * from ./lib/first-lib.module
export * from ./lib/first-component.module
export * from ./lib/second-component.module
// apps/app1/src/app/app.module.ts
import {FirstComponentModule, SecondComponentModule} from '@my-repo/first-lib'
I will assume you don't have standalone components to keep this answer short. Comment below if you have that situation then I will be justified to cover them.
Upvotes: 1
Reputation: 21638
The component needs to be added to a module and exported and then that module needs to be imported into your application.
Upvotes: 3