How to share code between projects ?
I have two apps created using:
ng generate application app1
ng generate application app2
I want projects/app1/src/app.module.ts
to import a module from projects/app2/src/shared/common.module.ts
What is the best practice for this without creating a 3rd project called common or something ? Create a projects/common or just have a folder called common
and plate TypeScript files here and import them.
By using git submodules , you can have an independent repository inside a parent repository. So you have your web and mobile repository and then inside it, in a folder, the shared code repository. If you cd into the shared code folder, you can pull, commit, make branches and push back to the shared code.
To get started, go ahead and install bit-cli, then head over to the project from which to share the components, and initialize a bit workspace. Then, head over to bit. dev and create a free account. Then, create a collection to host your shared components.
Use library projects!
ng generate library common
This will automatically add path aliases to the main tsconfig.json
"common": [
"dist/prod/common"
],
"common/*": [
"dist/prod/common/*"
]
Which will allow you to refer to the modules and exported components, services and pipes defined in the common
library project.
For example in any of your app.module.ts
:
import { SharedModule } from 'common';
@NgModule({
imports: [
SharedModule,
...
],
declarations: [...],
exports: [...]
bootstrap: [AppComponent]
})
export class AppModule { }
An alternative to support hot-reloading during ng serve
of a consuming app (say, for development) is to import from the common public_api
from the project level, as follows:
import { SharedModule } from 'projects/common/src/public_api';
@NgModule({
imports: [
SharedModule,
...
],
...
})
export class AppModule { }
Give it a try, I've used it heavily and it works marvels! I strongly recommend you read Angular Docs - Creating libraries.
If the majority of Apps share the common code, I will suggest another approach using dynamic routing and lazy-loading modules. Within the same code base, you can add all App specific code into a new Module. Then you add a additional flag in the environment file, and create a new environment file, so the App can be built into different bundle by the internment configuration --c. for more details, have a look this article
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With