2

我正在尝试让 Webpack Module Federation 与 NextJS 应用程序一起使用,其中联合模块使用样式化组件。如果我只使用 react 和 react-dom 但使用 styled-components 会给我这些错误,我的配置会按预期工作:

It looks like there are several instances of 'styled-components' initialized in this application. This may cause dynamic styles to not render properly, errors during the rehydration process, a missing theme prop, and makes your application bigger without good reason.

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

我尝试了通过修改主机和远程应用程序中的 Webpack 配置来将样式化组件解析为单个实例的不同方法,但似乎都失败了。

这是我当前的配置:

联合模块仓库(webpack.config.js):

const { ModuleFederationPlugin } = require("webpack").container;
const deps = require("./package.json").dependencies;
const path = require("path");

module.exports = {
  mode: "development",
  devServer: {
    contentBase: path.join(__dirname, "dist"),
    port: 3001,
  },
  output: {
    publicPath: "auto",
  },
  resolve: {
    extensions: [".js"],
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: /node_modules/,
        options: {
          plugins: [
            ["babel-plugin-styled-components", { pure: true, ssr: true }],
          ],
          presets: ["@babel/preset-react"],
        },
      },
    ],
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "remoteLib",
      filename: "remoteEntry.js",
      exposes: {
        "./Button": "./src/Button",
      },
      shared: {
        ...deps,
        react: {
          singleton: true,
          requiredVersion: deps.react,
        },
        "react-dom": {
          singleton: true,
          requiredVersion: deps["react-dom"],
        },
        "styled-components": {
          singleton: true,
          requiredVersion: deps["styled-components"],
        },
      },
    }),
  ],
};

使用 NextJS 应用程序 Webpack 配置(next.config.js):

webpack: (config, options) => {
    const { ModuleFederationPlugin } = options.webpack.container;

    config.plugins.push(
        new ModuleFederationPlugin({
            remotes: {
                'federated-components': 'remoteLib@http://localhost:3001/remoteEntry.js'
            }
        })
    );

    return config;
}
4

0 回答 0