angular 6-在项目之间共享通用代码的最佳实践 [英] angular 6 - best practice of sharing common code between projects

查看:250
本文介绍了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

这篇关于angular 6-在项目之间共享通用代码的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆