angular 6 - best practice of sharing common code between projects

江枫思渺然 提交于 2019-11-27 18:38:29

问题


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.


回答1:


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 this document:

  • https://github.com/angular/angular-cli/wiki/stories-create-library


来源:https://stackoverflow.com/questions/51253440/angular-6-best-practice-of-sharing-common-code-between-projects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!