모듈 및 컴포넌트 공유
원격 애플리케이션의 컴포넌트를 공개하고 호스트 애플리케이션에서 사용하는 방법을 학습합니다.
모듈 및 컴포넌트 공유은(는) CoddyKit의 무료 Micro Frontends Architecture with Module Federation 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Micro Frontends Architecture with Module Federation 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Micro Frontends Architecture with Module Federation 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to Module Sharing
In this lesson, we'll dive into the heart of Micro Frontends: sharing code!
We'll learn how one application can "expose" its components or modules, and how another application can "consume" them. This is key to building truly independent yet collaborative federated apps.
Understanding Exposed Modules
An exposed module is a piece of code (like a React component, a utility function, or even a data store) that one Micro Frontend application decides to make available to other applications.
- Think of it like publishing a library.
- The application making it available is called the Remote Application.
- It's configured within the Remote's Webpack setup.
How a Remote Exposes
To expose a module, you configure the ModuleFederationPlugin in your remote application's webpack.config.js. The exposes property is where the magic happens.
You define a public name for the module and point it to its local path.
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
// ... other webpack config ...
plugins: [
new ModuleFederationPlugin({
name: 'remoteApp',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/components/Button.jsx',
'./Header': './src/components/Header.jsx'
},
shared: ['react', 'react-dom']
})
]
};Example: Our Shared Button
Let's imagine a simple React button component that our remote application wants to share. This component lives in ./src/components/Button.jsx.
It's just a regular React component until we expose it.
// src/components/Button.jsx
import React from 'react';
const Button = ({ onClick, children }) => {
return (
<button
onClick={onClick}
style={{
padding: '10px 20px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer'
}}
>
{children}
</button>
);
};
export default Button;Consuming Remote Modules
On the flip side, a remote module is a module that an application wants to use, but it's hosted by another federated application.
- The application consuming it is called the Host Application.
- The Host needs to know where to find the Remote Application's exposed modules.
How a Host Consumes
The host application also uses the ModuleFederationPlugin. Here, you define the remotes property, mapping a local alias to the remote application's entry point.
The entry point is typically remoteEntry.js, generated by the remote app's Webpack build.
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
// ... other webpack config ...
plugins: [
new ModuleFederationPlugin({
name: 'hostApp',
remotes: {
remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js'
},
shared: ['react', 'react-dom']
})
]
};Importing & Using Shared Components
Once configured, the host application can import the remote component as if it were a local module. Webpack (via Module Federation) handles the dynamic loading from the remote URL.
Try running this simple example:
// This simulates a host app importing a remote component.
// In a real setup, 'remoteApp/Button' would resolve to the
// component exposed by the 'remoteApp' through Module Federation.
import React from 'react';
import ReactDOM from 'react-dom/client';
// Imagine 'remoteApp/Button' is the component we exposed earlier
// This import is resolved by Webpack's Module Federation Plugin
const RemoteButton = React.lazy(() => import('remoteApp/Button'));
function App() {
return (
<div>
<h1>Host Application</h1>
<React.Suspense fallback={<div>Loading Remote Button...</div>}>
<RemoteButton onClick={() => alert('Button Clicked!')}>
Click Me From Remote!
</RemoteButton>
</React.Suspense>
</div>
);
}
// Full entry point for a runnable React app
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);Behind the Scenes: Dynamic Loading
When the host application tries to import remoteApp/Button, Webpack doesn't look for it in the local node_modules. Instead, it uses the remotes configuration to:
- Fetch the
remoteEntry.jsfrom the specified URL. - Load the exposed
Buttonmodule from within that remote entry. - This happens dynamically at runtime, allowing independent deployments!
Best Practices for Sharing
When defining your exposes and remotes, keep these tips in mind:
- Clear Naming: Use descriptive names for your exposed modules (e.g.,
./UserProfileCard). - Consistent Aliases: Ensure your remote aliases in the host are easy to understand (e.g.,
marketingApp). - Relative Paths: Use relative paths (
./src/...) for exposed modules within the remote app.
Test Your Understanding
You've learned how to expose and consume modules. Let's check your understanding of the core configuration!
Lesson Summary & Next Steps
Great job! You've learned the fundamental mechanics of sharing modules with Webpack Module Federation:
- Exposing: Remote apps use
exposesto make components public. - Consuming: Host apps use
remotesto import and use those components. - This dynamic loading allows for independent development and deployment.
Next, we'll build a simple federated application from scratch, putting these concepts into practice!
자주 묻는 질문
“모듈 및 컴포넌트 공유” 강의는 무료인가요?
네 — “모듈 및 컴포넌트 공유” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Micro Frontends Architecture with Module Federation 강의 전체를 잠금 해제할 수 있습니다. Micro Frontends Architecture with Module Federation 강의에는 총 4개의 강의가 포함되어 있습니다.
“모듈 및 컴포넌트 공유”에서 뭘 배우나요?
원격 애플리케이션의 컴포넌트를 공개하고 호스트 애플리케이션에서 사용하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Micro Frontends Architecture with Module Federation을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Micro Frontends Architecture with Module Federation을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Micro Frontends Architecture with Module Federation은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“모듈 및 컴포넌트 공유” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Micro Frontends Architecture with Module Federation 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Micro Frontends Architecture with Module Federation 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 프로젝트 설정 및 구성
- 모듈 및 컴포넌트 공유
- 간단한 모듈 연합 앱 구축
- 페더레이션 앱 로컬 실행 및 디버깅