gpt4 book ai didi

javascript - Webpack 5 模块联合 - 远程模块中的 Hook - 不起作用

转载 作者:行者123 更新时间:2023-12-04 12:57:48 26 4
gpt4 key购买 nike

我正在尝试借助 Module Federation(webpack 5 功能)在运行时获得一个动态系统。一切都很好,但是当我将钩子(Hook)添加到“生产者”模块(主机应用程序从中动态导入组件的模块)时,我得到了大量“无效的钩子(Hook)规则”错误。

Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see [LINK RULES OF HOOKS]
Warning: React has detected a change in the order of Hooks called by PluginHolder. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: [LINK RULES OF HOOKS]
我已经使用了 externals 字段并在 html 文件中添加了脚本标记,我使用了 shared 选项来添加单例字段:true 并指定 react 和 react-dom 版本
每次控制台吐出大量错误
这是我直接从文档中加载模块的方法
const loadComponent = (scope: string, module: string) => async (): Promise<any> => {
// @ts-ignore
await __webpack_init_sharing__('default');
// @ts-ignore
const container = window[scope];
// @ts-ignore
await container.init(__webpack_share_scopes__.default);
// @ts-ignore
const factory = await window[scope].get(module);
return factory();
};
要加载 remoteEntry.js 文件,我使用 makeAsyncScriptLoader HOC 和 react-async-script,如下所示:
const withScript = (name: string, url: string) => {
const LoadingElement = () => {
return <div>Loading...</div>;
};

return () => {
const [scriptLoaded, setScriptLoaded] = useState<boolean>(false);

const AsyncScriptLoader = makeAsyncScriptLoader(url, {
globalName: name,
})(LoadingElement);

if (scriptLoaded) {
return <PluginHolder name={name}/>;
}

return (
<AsyncScriptLoader
asyncScriptOnLoad={() => {
setScriptLoaded(true);
}}
/>
);
};
};
PluginHolder 是一个简单的组件,它从加载的脚本中包装加载模块(加载完成)
 useEffect((): void => {
(async () => {
const c = await loadComponent(name, './Plugin')();
setComponent(c.default);
})();
}, []);

return cloneElement(component);
最重要的是启动器:
const [plugins, setPlugins] = useState<PluginFunc[]>([]);

useEffect((): void => {
pluginNames.forEach(desc => {
const loaded = withScript(desc.name, desc.url);
setPlugins([...plugins, loaded]);
});
}, []);
我不使用 React.Lazy,因为我不能使用 import()。更重要的是,在主机应用程序中,我设置了字段 eager: true in react 和 react-dom
我的 webpack.config.js(主机)如下:
require('tslib');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { DefinePlugin } = require('webpack');
const { ModuleFederationPlugin } = require('webpack').container;
// @ts-ignore
const AutomaticVendorFederation = require('@module-federation/automatic-vendor-federation');
const packageJson = require('./package.json');
const exclude = ['babel', 'plugin', 'preset', 'webpack', 'loader', 'serve'];
const ignoreVersion = ['react', 'react-dom'];

const automaticVendorFederation = AutomaticVendorFederation({
exclude,
ignoreVersion,
packageJson,
shareFrom: ['dependencies', 'peerDependencies'],
ignorePatchVersion: false,
});

module.exports = {
mode: 'none',
entry: {
app: path.join(__dirname, 'src', 'index.tsx'),
},
target: 'web',
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: '/node_modules/',
use: 'ts-loader',
},
{
test: /\.(s[ac]|c)ss$/i,
exclude: '/node_modules/',
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.html'),
favicon: path.join(__dirname, 'public', 'favicon.ico'),
}),
new DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
new ModuleFederationPlugin({
name: 'host',
remotes: {},
exposes: {},
shared: {
...automaticVendorFederation,
react: {
eager: true,
singleton: true,
requiredVersion: packageJson.dependencies.react,
},
'react-dom': {
eager: true,
singleton: true,
requiredVersion: packageJson.dependencies['react-dom'],
},
},
}),
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
publicPath: 'http://localhost:3001/',
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 3001,
},
};
还有我来自第二个模块的 webpack.config.js:
require('tslib');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { DefinePlugin } = require('webpack');
const { ModuleFederationPlugin } = require('webpack').container;
// @ts-ignore
const AutomaticVendorFederation = require('@module-federation/automatic-vendor-federation');
const packageJson = require('./package.json');
const exclude = ['babel', 'plugin', 'preset', 'webpack', 'loader', 'serve'];
const ignoreVersion = ['react', 'react-dom'];

const automaticVendorFederation = AutomaticVendorFederation({
exclude,
ignoreVersion,
packageJson,
shareFrom: ['dependencies', 'peerDependencies'],
ignorePatchVersion: false,
});

module.exports = (env, argv) => {

const { mode } = argv;
const isDev = mode !== 'production';

return {
mode,
entry: {
plugin: path.join(__dirname, 'src', 'index.tsx'),
},
target: 'web',
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: '/node_modules/',
use: 'ts-loader',
},
{
test: /\.(s[ac]|c)ss$/i,
exclude: '/node_modules/',
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.html'),
favicon: path.join(__dirname, 'public', 'favicon.ico'),
}),
new DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
new ModuleFederationPlugin({
name: 'example',
library: { type: 'var', name: 'example' },
filename: 'remoteEntry.js',
remotes: {},
exposes: {
'./Plugin': './src/Plugin',
},
shared: {
...automaticVendorFederation,
react: {
eager: isDev,
singleton: true,
requiredVersion: packageJson.dependencies.react,
},
'react-dom': {
eager: isDev,
singleton: true,
requiredVersion: packageJson.dependencies['react-dom'],
},
},
}),
],
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: 'http://localhost:3002/',
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 3002,
},
};
};
您是否有任何经验或任何线索 - 我认为关键是 2 个应用程序使用了 2 个 react 实例,但这些是我的猜测。
我的配置有问题吗?

最佳答案

确保将共享依赖项添加到 webpack.config 文件中。
请参见下面的示例:

  plugins: [
new ModuleFederationPlugin(
{
name: 'MFE1',
filename:
'remoteEntry.js',

exposes: {
'./Button':'./src/Button',
},
shared: { react: { singleton: true }, "react-dom": { singleton: true } },
}
),
new HtmlWebpackPlugin({
template:
'./public/index.html',
}),
],
};
我有这个共享属性的主机和远程项目设置。当钩子(Hook)破坏了我的主机应用程序时,为我修复了它。这是因为存在重复的react依赖,无论版本是否相同,都会出现此错误。

关于javascript - Webpack 5 模块联合 - 远程模块中的 Hook - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63942391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com