MSA
[MFA] Module Federation 다른 서버 TypeScript Type 추론 Example (명시적 정의, @module-federation/typescript)
차노도리
2024. 1. 21. 21:48
Module Federation에서 Remote App 모듈 사용 시 Type 추론이 자동으로 되지 않는다.
방법 1. 명시적으로 정의하여 타입 추론
- Monorepo프로젝트 진행 중일 경우 Remote App 경로를 명시적으로 정의하여 타입 추론이 가능하다.
- 장점
- 경로 명시적으로 정의되어 있어, 어떤 컴포넌트에서 오는지 쉽게 파악 가능
- 실제 경로를 참조하여 오류를 최소화할 수 있음
- tsconfig 설정만으로 간단하게 사용가능
- 단점
- 모노레포 구조에서만 사용 가능
{
// ...생략
"compilerOptions": {
// ...생략
"paths": {
"gugbab_component_app/Button": ["../gugbab-component-app/src/components/Button"]
}
}
}
방법 2. @module-federation/typescript 활용하여 타입 추론하기
- Remote App 서버가 구동 중일 때 사용 가능
- Host App에서 Remote App의 타입 정보를 가져와서 추론
- https://github.com/module-federation/typescript
- 장점
- Remote App의 타입 정보를 최신 상태로 관리하기 쉽다.
- Monorepo 뿐만 아니라 Multirepo 구조에서도 적용 가능
- 단점
- 타입 정보를 원격 서버에서 직접 가져오기 때문에, 원격 서버가 구동 중이어야 한다.
- 외부 라이브러리에 의존하게 되어, 라이브러리 업데이트나, 호환성 영향을 받을 수 있다.
Host App, Remote App 공통 작업
- @module-federation/typescript 모듈 받기
- webpack config `FederatedTypesPlugin`에 기존 federationConfig 추가하기
ex) webpack.config.js
const { FederatedTypesPlugin } = require("@module-federation/typescript");
// ...생략
module.exports = (_, argv) => ({
// ...생략
plugins: [
// ...생략
new ModuleFederationPlugin(federationConfig),
new FederatedTypesPlugin({ federationConfig }),
],
});
Host App 추가 작업
- tsconfig에 타입 경로 추가하기
{
"compilerOptions": {
// ...생략
"paths": {
"*": ["./@mf-types/*"]
}
}
}