You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用gulp+babel构建的SSR React项目在IE11/9等IE浏览器中无法运行

解决方案

1. 调整React版本

React 18及以上版本已官方停止支持IE浏览器,若需要兼容IE9/IE11,请先将React、ReactDOM降级到17.x或更低的兼容版本。

2. 修改.babelrc配置

你当前的@babel/preset-env没有指定兼容目标和polyfill规则,调整配置如下:

{
    "sourceType": "unambiguous",
    "presets": [
        ["@babel/preset-env", {
            "targets": {
                "ie": "9",
                "browsers": ["last 2 versions", "ie >= 9"]
            },
            "useBuiltIns": "usage",
            "corejs": 3
        }],
        ["@babel/preset-react", {
            "runtime": "automatic"
        }]
    ]
}

说明:

  • 移除冗余的@babel/plugin-transform-react-jsx插件,该能力已包含在@babel/preset-react中
  • useBuiltIns: "usage"会自动按需注入所需的polyfill,无需手动引入@babel/polyfill
  • 需提前安装依赖:npm install --save core-js@3 @babel/runtime-corejs3

3. 调整gulp构建任务

你当前的构建配置存在多个问题:

  • 手动引入了React、ReactDOM的预编译min文件,还错误引入了仅服务端可用的react-dom/server.node.js,这些都不需要加到入口中
  • babelify默认不转译node_modules下的依赖,会导致React等包的ES6+语法未被转译
  • 旧版uglify不支持ES6语法压缩,需替换为兼容更好的terser
  • sourcemap初始化顺序错误

调整后配置如下,先安装依赖:npm install --save-dev gulp-terser

const terser = require('gulp-terser');

gulp.task('js-react', function() {
    const b = browserify({
        entries: [
            'js/shared/react/index.js'
        ],
        debug: true
    });

    return b
        .transform(babelify, {
            global: true,
            // 配置需要转译的node_modules依赖
            ignore: [/node_modules\/(?!(react|react-dom)\/).*/]
        })
        .bundle()
        .pipe(source('react-client-side.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(terser())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('.path-to-file'));
});

4. 调整客户端代码

IE浏览器不存在global全局对象,需做兼容处理:

import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './components/MyComponent';

// 兼容IE全局对象
window.global = window;

window.hydrator = (props = {}) => {
    ReactDOM.hydrate(<MyComponent {...props}/>, document.getElementById('root'));
};

箭头函数、默认参数等语法会被babel自动转译为IE兼容的ES5语法,无需手动修改。

5. 补充特殊场景polyfill

如果你的项目用到了前端路由、Fetch API等IE原生不支持的能力,需要额外补充对应的polyfill,core-js已覆盖了绝大多数ES6+API的兼容,特殊需求可单独引入对应polyfill即可。

内容的提问来源于stack exchange,提问作者manosagent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:18:03