React Module Federation을 이용한 Lazy Loading 예제를 통해 이를 더욱 자세히 알아보겠습니다.
Host 애플리케이션에서는 다음과 같이 webpack.config.js 파일을 설정합니다.
import path from 'path';
import { Configuration } from 'webpack';
import { ModuleFederationPlugin } from 'webpack/container';
const config: Configuration = {
mode: 'development',
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 3000,
},
output: {
publicPath: '<http://localhost:3000/>',
},
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
remoteApp: 'remoteApp@<http://localhost:3001/remoteEntry.js>',
},
shared: ['react', 'react-dom'],
}),
],
};
export default config;
위의 설정에서 name은 현재 애플리케이션의 이름을, remotes는 현재 애플리케이션이 사용할 원격 애플리케이션의 정보를, shared는 원격 애플리케이션과 공유할 모듈을 설정합니다.
Remote 애플리케이션에서는 다음과 같이 webpack.config.js 파일을 설정합니다.
import path from 'path';
import { Configuration } from 'webpack';
import { ModuleFederationPlugin } from 'webpack/container';
const config: Configuration = {
mode: 'development',
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 3001,
},
output: {
publicPath: '<http://localhost:3001/>',
library: { type: 'var', name: 'remoteApp' },
},
plugins: [
new ModuleFederationPlugin({
name: 'remoteApp',
library: { type: 'var', name: 'remoteApp' },
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/Button',
},
shared: ['react', 'react-dom'],
}),
],
};
export default config;
위의 설정에서 name은 현재 애플리케이션의 이름을, filename은 현재 애플리케이션이 생성할 파일 이름을, exposes는 현재 애플리케이션이 제공하는 모듈을 설정합니다.
Host 애플리케이션에서는 다음과 같이 Lazy Loading을 통해 Remote 애플리케이션의 모듈을 사용할 수 있습니다.
import React, { lazy, Suspense } from 'react';
const RemoteButton = lazy(() => import('remoteApp/Button'));
function App() {
return (
<div>
<h1>Host Application</h1>
<Suspense fallback={<div>Loading...</div>}>
<RemoteButton />
</Suspense>
</div>
);
}
export default App;
위의 코드에서는 Suspense와 lazy 함수를 이용하여 RemoteButton 모듈을 Lazy Loading합니다. 이를 통해 Remote 애플리케이션의 모듈을 필요한 시점에 로드하여 사용할 수 있습니다.