使用 webpack 5,您现在可以通过module federation来做到这一点。
基本思想是您“公开”一个项目的导出以在另一个项目中使用:
App 1(使用 app2 中的 Button)
<!-- 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",
}),
]
App 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"],
})
]
这是一个包含各种示例的存储库。