【发布时间】:2021-05-13 08:05:51
【问题描述】:
我正在研究 Webpack 5 模块联合功能,但无法理解为什么我的代码不起作用。 这个想法与标准模块联合示例所做的非常相似:
app1 - 是主机应用程序
app2 - 是将整个应用程序暴露给app1的远程对象
(app1 渲染标题和水平线,下面应该渲染app2)
app1 和 app2 都在 weback.config.js 中声明 react 和 react-dom 作为它们共享的、单例的、急切的依赖项:
// app1 webpack.config.js
module.exports = {
entry: path.resolve(SRC_DIR, './index.js');,
...
plugins: [
new ModuleFederationPlugin({
name: "app1",
remotes: {
app2: `app2@//localhost:2002/remoteEntry.js`,
},
shared: { react: { singleton: true, eager: true }, "react-dom": { singleton: true, eager: true } },
}),
...
],
};
// app2 webpack.config.js
module.exports = {
entry: path.resolve(SRC_DIR, './index.js');,
...
plugins: [
new ModuleFederationPlugin({
name: "app2",
library: { type: "var", name: "app2" },
filename: "remoteEntry.js",
exposes: {
"./App": "./src/App",
},
shared: { react: { singleton: true, eager: true }, "react-dom": { singleton: true, eager: true } },
}),
...
],
};
在 App1 index.js 我有下一个代码:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
App1 App.js 组件是下一个:
import React, { Suspense } from 'react';
const RemoteApp2 = React.lazy(() => import("app2/App"));
export default function App() {
return (
<div>
<h1>App 1</h1>
<p>Below will be some content</p>
<hr/>
<Suspense fallback={'Loading App 2'}>
<RemoteApp2 />
</Suspense>
</div>
);
}
但是当我启动应用程序时,我得到了下一个错误:
Uncaught Error: Shared module is not available for eager consumption: webpack/sharing/consume/default/react/react?1bb3
at Object.__webpack_modules__.<computed> (consumes:133)
at __webpack_require__ (bootstrap:21)
at fn (hot module replacement:61)
at Module../src/index.js (main.bundle.a8d89941f5dd9a37d429.js:239)
at __webpack_require__ (bootstrap:21)
at startup:4
at startup:6
如果我从index.js 到bootstrap.js 和index.js 中提取所有内容就可以了
import('./bootstrap');
一切正常。
这让我感到困惑,因为来自创建者的 official docs 和 blog posts 声明您可以采用 bootstrap.js 方式或将依赖项声明为急切的方式。
如果没有bootstrap.js 模式,如果它无法工作,我们将不胜感激。
这是我正在构建的完整 GitHub 沙箱的链接:https://github.com/vovkvlad/webpack-module-fedaration-sandbox/tree/master/simple
【问题讨论】:
标签: javascript reactjs webpack webpack-5 webpack-module-federation