programing

Angular2 : CoreModule 대 SharedModule

luckcodes 2021. 1. 17. 11:30

Angular2 : CoreModule 대 SharedModule


사람은 무엇을 설명 할 수 SharedModuleCoreModule스탠드를?

나는 각도 프로젝트를 구축하기 위해이 접근 방식을 사용하는 여러 프로젝트를 지켜 왔습니다.

  1. 두 개의 모듈이 필요한 이유는 무엇입니까?
  2. 각 항목을 언제 가져와야합니까?
  3. 어느 imports, exports, declarations각각의 하나는해야합니까?

TLDR :

  1. CoreModule단지이 있어야 services만 한 번에 가져올 수 AppModule.
  2. SharedModule무엇을해야하지만, services과 (또한이 될 수있는 공유 물건을 필요로하는 모든 모듈에서 가져올 수 AppModule).

그러나:

실제 모듈은 종종 [위] 지침에서 의도적으로 벗어난 하이브리드입니다. 이 지침은 법률이 아닙니다. 달리 할 합당한 이유가 없다면 그들을 따르십시오.


RTFM :

따라서 전체 NgModules의 문서 (컨텍스트를 이해하기위한 몇 가지 다른 내용 포함)를 살펴본두 번째 및 세 번째 질문에 대한 답을 쉽게 찾았 습니다 . 여기에 있습니다.

SharedModule

  • 만들기 SharedModule와 함께 components, directives그리고 pipes당신은 당신의 응용 프로그램에서 모든 곳에서 사용하는 것이. 이 모듈은 전적으로로 구성되어야 declarations하며 대부분은 내 보냅니다.
  • SharedModule수 재수출 다른 위젯과 같은 모듈 CommonModule, FormsModuleUI가 컨트롤 및 모듈 당신이 가장 널리 사용하는 것이.
  • SharedModule하지 말았어야 providers이유는 이전에 설명합니다. 가져 오거나 다시 내 보낸 모듈에 공급자가 있어서도 안됩니다. 이 지침에서 벗어난 경우 수행중인 작업과 이유를 파악하십시오.
  • SharedModule앱이 시작될 때로드 된 모듈과 나중에 지연로드하는 모듈 모두에서 기능 모듈을 가져옵니다 .

CoreModule

  • 애플리케이션이 시작될 때로드하는 싱글 톤 서비스에 대해 CoreModulewith providers작성하십시오 .
  • CoreModule루트 AppModule로만 가져 옵니다 . CoreModule다른 모듈로 가져 오지 마십시오 .
  • CoreModule없는 순수한 서비스 모듈을 만드는 것을 고려하십시오 declarations.

TLDR버전 보다 더 자세 하고 코딩을 계속할 수 있지만 이해하기 위해 문서를 읽어야하는 몇 가지 사항이 언급되어 있습니다 (예 : '위젯 모듈', '이전 설명 이유', '순수 서비스 모듈'). ), 또한 첫 번째 질문에 대답하지 않습니다 .

그러니 그렇게 해보자!


두 개의 모듈이 필요한 이유는 무엇입니까?

당신은 필요하지 않은 두 개의 모듈을. 이것은 문서에있는 것입니다.

루트 모듈은 몇 가지 구성 요소가있는 간단한 응용 프로그램에 필요한 모든 것입니다.

그렇기 때문에 먼저 다른 질문을하는 것이 중요합니다.

사람들이 프로젝트를 여러 모듈로 구성하는 이유는 무엇입니까?

이에 대한 기본 설명은 문서에서 위의 설명 바로 뒤에 나옵니다.

앱이 성장함에 따라 루트 모듈을 관련 기능 모음을 나타내는 기능 모듈로 리팩터링합니다. 그런 다음 이러한 모듈을 루트 모듈로 가져옵니다.

하지만 "왜?" 그리고 이것은 기본적인 설명 이상의 것을 요구합니다. 이제 앱이 성장하기 시작하고 기능을 기능 모듈로 분리하지 않으면 발생할 수있는 몇 가지 문제설명하기 시작하겠습니다 .

  • 루트 모듈은 모든 종속성 (예 : 타사 모듈)을 가져오고 모든 서비스를 제공하고 모든 구성 요소, 지시문 및 파이프를 선언해야하기 때문에 읽고 작업하기 어려운 코드로 복잡해지기 시작합니다. 앱이 더 많이 필요할수록이 모듈은 더 커집니다.
  • 서로 다른 기능에는 명확한 경계가 없기 때문에 앱의 구조를 이해하는 것뿐만 아니라 팀에서 다른 책임을 갖는 것이 더 어렵습니다.
  • 앱의 다른 부분 간의 충돌을 해결해야 할 수 있습니다. 예를 들어 앱의 서로 다른 두 부분에서 동일한 작업을 수행하는 지시문 또는 구성 요소가있는 경우 더 긴 이름을 사용하여 구분하거나 가져올 때 이름을 변경해야합니다.

위의 예가 정확히 문제가 아니라고 생각할 수 있지만 (혼자서 일하고 자신의 엉망으로 살 수 있거나 모든 팀원도 지저분 할 수 있음) 다른 사람들이 당신과 동의하지 않을 수 있다는 점을 명심하십시오. "이 접근법을 사용하여 여러 프로젝트를 지켜 봤습니다 . " .

이에 동의하고 성장하는 앱을 기능 모듈로 구성하고 싶다는 점을 고려할 때 문서에서 다음 설명을 참조하십시오.

루트 모듈과 기능 모듈은 동일한 실행 컨텍스트를 공유합니다. 그들은 동일한 의존성 주입기를 공유하므로 한 모듈의 서비스를 모두가 사용할 수 있습니다.

모듈에는 다음과 같은 중요한 기술적 차이점이 있습니다.

  • 앱을 시작하려면 루트 모듈을 부팅합니다. 앱을 확장하기 위해 기능 모듈을 가져옵니다.
  • 기능 모듈은 다른 모듈에서 구현을 노출하거나 숨길 수 있습니다.

잊지 말아야 할 정보 : "한 모듈의 서비스는 모든 [모듈]에서 사용할 수 있습니다.", 구성 요소, 지시문 및 파이프와 같은 다른 것들은 사용하려는 각 모듈에 삽입되어야합니다.

이 정보를 사용하여 다음 질문에 답하여 알고 싶은 내용에 더 가까이 다가 갈 수 있습니다.

모든 기능 모듈이 동일합니까?

아니! 최소한 루트 모듈 만 있으면 안되지만 원하는 것은 무엇이든 할 수 있다는 것이 제안 되었기 때문에 동일하지 않아야합니다. 하지만 그렇게해서는 안됩니다.

문서에는 제안 된 기능 모듈 그룹 간의 차이점을 보여주는 표가 있습니다. 그 일부를 살펴 보겠습니다.

FEATURE   SHOULD HAVE    SHOULD HAVE   SHOULD HAVE
MODULE    DECLARATIONS   PROVIDERS     EXPORTS         

Domain    Yes            Rare          Top component   
Routed    Yes            Rare          No              
Routing   No             Yes (Guards)  RouterModule    
Service   No             Yes           No              
Widget    Yes            Rare          Yes             

주의! 그들은 이것이 이것이 ...

... 몇 가지 애플리케이션에서 NgModules를 사용한 초기 경험을 기반으로 한 예비 지침.

다시 말하지만,이 가이드 라인에 집착하지 않고 편차가 발생할 수 있지만, 무엇을하고 있고 그 이유를 알아야합니다.

이제이 테이블을 분석해 보겠습니다.

  • ServiceWidget그룹은 각 열에 그들 사이에 완전히 다른 값을 가질 수있는 유일한 사람입니다.
  • DomainRouted그룹은 기본적으로 동일 Widget제한된 또는 없음 수출과 함께 그룹.
  • Routing그룹은 기본적으로 Service그룹이며 내보내기 예외가 있으며 특정 공급자로 제한됩니다.

그래서,하자가 생각 Domain, Routed그리고 Routing그룹은 변종 Service또는 Widget마지막 두에 초점을합니다.

서비스 는 여러분의주의를 끌 것입니다. "한 모듈의 서비스를 모든 [모듈]에서 사용할 수있다"는 사실을 잊지 말아야합니다. 글쎄, 그들이 기능 모듈 그룹을 호출한다면 Services, 그것은 한 번만 가져올 수 있도록 다른 모듈과 격리되어야하기 때문입니다. 예를 들어, 당신은 할 수 있습니다 UserModule와 같은 서비스로 구성하는 SignUpService, SignInService, SocialAuthServiceUserProfileService. 가져 오는 곳마다 UserModule모든 서비스를 앱 전체에서 사용할 수 있습니다. 그리고 위의 표에 따라 선언이나 내보내기가 없어야하며 공급자 만 있어야합니다.

위젯은 더 일반적으로 들리지만 뭔가를 알려줄 것입니다. "컴포넌트, 디렉티브 및 파이프와 같은 다른 것들은 사용하려는 각 모듈에 주입되어야합니다."라는 사실도 잊지 말아야 합니다. ? 그래서 이것이 여러분이 사용할 모듈의 유형입니다. 예를 들어, 당신은 할 수 UIModule와를 ButtonComponent, NavComponent, SlideshowComponent, HighlightLinkDirective, CtaPipe. 내 보낸 요소 중 하나 또는 모두를 사용해야 할 때마다 UIModule.

따라서 기본적으로 Angular가 서비스를 처리하는 방식으로 인해 기능을 기능 모듈로 분할하기 시작할 때 서비스를 자체 모듈로 분리해야하며 다른 항목은 원하는대로 구성 할 수 있습니다.

이것에 어떻게 CoreModule그리고 SharedModule적합합니까?

간단하게하기 위해,이 CoreModuleA는 Service모듈과는 SharedModuleA는 Widget모듈. 그리고 이것이 AppModule필요한 모든 모듈 에서 첫 번째를 한 번만 가져오고 후자를 가져와야하는 이유 입니다. 내 예 이상에서,이 UserModule에 의해 수입 될 수 CoreModuleUIModule바이 SharedModule.

그러나 이전에 언급했듯이 다음은 지침이며 편차가 발생할 수 있습니다. 자체 예제에서도에서 구성 요소를 선언 CoreModule하지만 관찰은 다음과 같습니다.

이 페이지 샘플은 CoreModuleAppModule에서 선언 한 루트 AppComponent 내에서만 사용되는 두 구성 요소를 선언하고 [in the ] 내보냄으로써 해당 조언에서 벗어 납니다. 이 지침을 엄격히 따르는 사람은 대신 AppModule에서 이러한 구성 요소를 선언했을 것입니다.


개인적으로 가장 큰 혼란은 네이밍 선택에 관한 것입니다. 일반적으로 사람들은 앱의 핵심에 포함 된 모든 항목 (예 : 사용자 항목, NavBar,로드 바, 토스터 등)이으로 들어가고 CoreModule여러 기능에서 공유되는 모든 항목이 SharedModule.

모든 서비스가 "자연적으로"모든 모듈간에 공유되고 서비스가에 포함되어서는 안되며 SharedModulea NavbarComponent가 앱의 핵심의 일부이며 구성 요소가에 포함되어서 는 안되므로 실제로는 사실이 아니며 약간 오해의 소지가 있습니다 . CoreModule.

어쨌든 권장 사항은 그렇게하지 않을 이유를 찾을 때까지 지침을 따르는 것입니다.

가이드 라인을 더 잘 이해하는 데 도움이되는 위의 나머지 표는 다음과 같습니다.

FEATURE   CAN BE                 SOME
MODULE    IMPORTED BY            EXAMPLES

Domain    Feature, AppModule     ContactModule (before routing)
Routed    Nobody                 ContactModule, DashboardModule,
Routing   Feature (for routing)  AppRoutingModule, ContactRoutingModule
Service   AppModule              HttpModule, CoreModule
Widget    Feature                CommonModule, SharedModule

건배!


I do use this approach myself and here's why/how :
(it's one approach and maybe other people will have != ideas which is fine)

I like to keep the app.module as clean as possible. If you want to use universal or build your project with AOT (when not using angular-cli) you may need to have a duplicated app.module with small changes in all those files.

So if you import many modules into your app.module, you'll have to maintain that list up to date in different files.

Here comes the core.module :
Put every module you only want to import once here. Mainly, modules with forRoot methods (the ones that exports their providers and that should be imported only once).

Import also your providers here. (if you use ngrx for example, declare your store here).

Then, the shared.module :
Put every module you'll have to reuse across your app (CommonModule, HttpModule, RouterModule, MaterialModule, FlexLayoutModule, etc).

Finally, app.module :
Import in app.module your core.module ONLY HERE. CoreModule should be loaded only once. In all your submobules, you can load the SharedModule.

With that configuration, if you need to create another app.module for universal or others, you don't have to copy and maintain the whole module list in different files. Simply import the core.module and you're good to go.


As per style guide of Angular and my observations:

CoreModule(core.module.ts) Core feature module

All services that should be singleton should be provided here. For example HelperService, LoggerService.

Application wide component should be declared in CoreModule like header, footer.

CoreModule provides one or more singleton services. Angular registers the providers with the app root injector, making a singleton instance of each service available to any component that needs them, whether that component is eagerly or lazily loaded.

Only the root AppModule should import the CoreModule.

SharedModule(shared.module.ts) Shared feature module

declare components, directives, and pipes in a shared module when those items will be re-used and referenced by the components declared in other feature modules

It is suggested to avoid using services in shared modules. Services are usually singletons that are provided once for the entire application or in a particular feature module.

Modules required by all feature modules should be imported in SharedModule like CommonModule & FormsModule.

Declaration of sharable component/pipe/directive should be in SharedModule. If these component/pipe/directive needs to be used by other feature module, they must exported.

If using Material, it's best place to import and re-export Angular Material components.

References: CoreModule, SharedModule


I think this question is too general and for general question, you'll have general answers ... For example, shared module is meant to keep what several components/modules use :

import { NgModule }            from '@angular/core';
import { CommonModule }        from '@angular/common'; 
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

//import { AwesomePipe }         from './awesome.pipe';
//import { HighlightDirective }  from './highlight.directive';

@NgModule({
  exports:      [ /*AwesomePipe, HighlightDirective,*/
                  CommonModule, FormsModule, ReactiveFormsModule ]
})
export class SharedModule { }

CoreModule is more like what you consider to be the core of your page (Nav, Spinner, Alert...). This is very suggestive and depend on your feeling I think. For example:

import { NgModule, Optional, SkipSelf } from '@angular/core';

import { NavComponent } from './nav/nav.component';
import { SpinnerComponent } from './spinner/spinner.component';
import { SpinnerService } from './spinner/spinner.service';
import { AlertComponent }     from './alert/alert.component';
import { AlertService }       from './alert/alert.service';

import { SharedModule }       from '../shared/shared.module';

import { CoreRoutingModule } from './core-routing.module';


@NgModule({
  imports: [ 
    SharedModule, 
    CoreRoutingModule,
  ],
  exports: [//Other modules use these components, so we export them
    AlertComponent, 
    NavComponent, 
    SpinnerComponent,

    ],
  declarations: [ //we use them in CoreModule, so we declare them
    AlertComponent, 
    NavComponent, 
    SpinnerComponent,

    ],
  providers: [
    SpinnerService, 
    AlertService,

  ]
})
export class CoreModule {
    constructor (@Optional() @SkipSelf() parentModule: CoreModule) {
      if (parentModule) {
        throw new Error(
          'CoreModule est déjà chargé. Importer le uniquement dans AppModule');
      }
    }
}

ReferenceURL : https://stackoverflow.com/questions/42695931/angular2-coremodule-vs-sharedmodule