更新时间:2023-12-05 15:36:22
使用Webpack 5,您现在可以通过模块联盟.
With webpack 5 you can now do this via module federation.
基本思想是,您暴露"一个项目中的导出以用于另一个项目:
The basic idea is that you "expose" exports from one project to be used in another:
应用程序1(使用来自应用程序2的按钮)
<!-- public/index.html -->
<html>
<head>
<!-- remote reference to app 2 -->
<script src="http://localhost:3002/remoteEntry.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
//app.ts
import * as React from "react";
const RemoteButton = React.lazy(() => import("app2/Button"));
const App = () => (
<div>
<h1>Typescript</h1>
<h2>App 1</h2>
<React.Suspense fallback="Loading Button">
<RemoteButton />
</React.Suspense>
</div>
);
export default App;
//... webpack.config.js
plugins: [
new ModuleFederationPlugin({
name: "app1",
library: { type: "var", name: "app1" },
remotes: {
app2: "app2",
},
shared: ["react", "react-dom"],
}),
new HtmlWebpackPlugin({
template: "./public/index.html",
}),
]
应用2(显示按钮)
// src/Button.ts
import * as React from "react";
const Button = () => <button>App 2 Button</button>;
export default Button;
//... webpack.config.js
plugins: [
new ModuleFederationPlugin({
name: "app2",
library: { type: "var", name: "app2" },
filename: "remoteEntry.js",
exposes: {
Button: "./src/Button",
},
shared: ["react", "react-dom"],
})
]
这是一个回购,其中包含各种示例.