Module Federation远程应用加载时React未定义问题排查
问题:远程应用共享React后仍出现"React is not defined"报错
加载远程应用时出现如下报错:
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', }), ], };
可能的原因分析
TSX文件未显式引入React:如果你的TypeScript版本低于4.1,TSX编译后的代码会依赖全局的
React变量,必须在每个TSX文件顶部手动添加import React from 'react';。即使通过模块联邦共享了React,代码里没显式引入的话,webpack无法自动关联到共享模块。Babel未启用React自动引入:使用
@babel/preset-react时,若未配置runtime: 'automatic',编译后的代码依然会依赖全局React。需要在Babel配置中开启自动运行时,这样可以省去手动import React的步骤,同时确保代码使用模块级别的React:{ "presets": [ ["@babel/preset-react", { "runtime": "automatic" }], "@babel/preset-typescript" ] }共享依赖配置缺少
eager参数:远程应用的入口main.tsx可能在模块联邦初始化前就执行了,导致React还没被共享加载就被调用。给react的shared配置加上eager: true,确保它在模块联邦启动前优先加载:shared: { react: { import: 'react', shareKey: 'react', shareScope: 'default', singleton: true, eager: true // 新增这个参数 }, 'react-dom': { singleton: true, eager: true }, }宿主应用未同步配置共享React:模块联邦要求宿主和远程应用的共享依赖配置保持一致。如果宿主应用的webpack.config.js里没有把React加入shared列表,远程应用请求共享的React时会找不到,进而触发报错。需要在宿主应用中添加相同的shared配置。
内容的提问来源于stack exchange,提问作者Andrea Costanzo
相关产品推荐
相关产品推荐

