React 模块联合并未在 App 中定义

问题描述 投票:0回答:1

我有一个简单的远程应用程序,其配置如下,但是当我尝试将其加载到主机应用程序中时,尽管位于共享库中,但反应似乎未正确加载。可能是什么问题?

Uncaught ReferenceError: React is not defined
    at App (App.tsx:6:3)
    at renderWithHooks (react-dom.development.js:15486:18)
    at mountIndeterminateComponent (react-dom.development.js:20098:13)

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const ModuleFederationPlugin =
  require('@module-federation/enhanced').ModuleFederationPlugin;
const path = require('path');

module.exports = {
  entry: './src/main.tsx',
  mode: 'development',
  target: 'web',
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    port: 4200,
  },
  optimization: {
    runtimeChunk: false,
    splitChunks: {
      chunks: 'async',
    },
  },
  output: {
    publicPath: 'auto',
    path: path.join(__dirname, '../../dist/apps/remote_webpack'),
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'remote_webpack',
      filename: 'remoteEntry.js',
      exposes: {
        './Module': './src/remote-entry.ts',
      },
      shared: {
        react: {
          import: 'react',
          shareKey: 'react',
          shareScope: 'default',
          singleton: true,
        },
        'react-dom': {
          singleton: true,
        },
      },
    }),
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
  ],
};
webpack webpack-module-federation
1个回答
0
投票

反应< 17

我们需要在每个文件中显式导入 React

反应 >= 17

该问题与 babel 有关。无论是在

options > presets
中的 babel-loader 规则中的
webpack.config.json
中还是在
.babelrc
文件中,我们都需要为
runtime:"automatic"
指定
@babel/preset-react

.babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-typescript",
    ["@babel/preset-react", { "runtime": "automatic" }]
  ],
  "plugins": []
}

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.