问题描述
如何在项目之间共享代码?
我使用以下方法创建了两个应用:
ng 生成应用程序 app1
ng 生成应用程序 app2
我希望 projects/app1/src/app.module.ts
从 projects/app2/src/shared/common.module.ts
导入模块>
在不创建名为 common 或其他东西的第三个项目的情况下,最佳实践是什么?创建一个projects/common 或者只是有一个名为common
的文件夹并在此处放置TypeScript 文件并导入它们.
使用库项目!
ng 生成库 common
这会自动将路径别名添加到主 tsconfig.json
"common": [dist/prod/common"],常见的/*": [dist/prod/common/*"]
这将允许您引用在 common
库项目中定义的模块和导出的组件、服务和管道.
例如在您的任何 app.module.ts
中:
import { SharedModule } from 'common';@NgModule({进口:[共享模块,...],声明:[...],出口:[...]引导程序:[AppComponent]})导出类 AppModule { }
在消费应用程序的 ng serve
期间支持热重载的另一种方法是从项目级别从公共 public_api
导入,如如下:
import { SharedModule } from 'projects/common/src/public_api';@NgModule({进口:[共享模块,...],...})导出类 AppModule { }
试一试,我已经大量使用它,而且效果非常好!我强烈建议您阅读此文档:
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.
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:
这篇关于Angular – 在项目之间共享通用代码的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!