angular 6-在项目之间共享通用代码的最佳实践
如何在项目之间共享代码?
How to share code between projects ?
我创建了两个使用以下应用程序:
I have two apps created using:
ng生成应用程序app1
ng生成应用程序app2
我要 projects / app1 / src / app.module.ts
从 projects /中导入模块app2 / src / shared / common.module.ts
在没有创建名为common或something的第三个项目的情况下,最佳做法是什么?创建一个项目/普通项目,或者仅创建一个名为普通
的文件夹,并在此处放置TypeScript文件并导入它们。
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.
使用库项目!
ng generate library common
这将自动向主 tsconfig.json
"common": [
"dist/prod/common"
],
"common/*": [
"dist/prod/common/*"
]
将允许您引用 common
库项目中定义的模块以及导出的组件,服务和管道。
Which will allow you to refer to the modules and exported components, services and pipes defined in the common
library project.
例如在您的任何 app.module.ts
中:
import { SharedModule } from 'common';
@NgModule({
imports: [
SharedModule,
...
],
declarations: [...],
exports: [...]
bootstrap: [AppComponent]
})
export class AppModule { }
在 ng服务
期间支持热重装的替代方法消费型应用(例如,用于开发)是从项目级别的普通 public_api
导入的,如下所示:
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