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

使用React新API报错:Module not found: Can't resolve 'react-dom/client'

React升级问题解决:createRoot模块找不到与依赖冲突

一、createRoot 模块找不到的问题

原因

createRoot 是React 18新增的API,你的项目里react和react-dom版本低于18,所以找不到react-dom/client这个模块,只能用旧版的ReactDOM.render。

解决办法

升级react和react-dom到18.x版本:

npm install react@^18 react-dom@^18

或用yarn:

yarn add react@^18 react-dom@^18

升级后注意容器元素的id要和HTML文件里的对应(你的代码里用的是app,旧代码用的是root,需要统一),createRoot代码就能正常运行。

二、react-scripts@5.0.1与typescript@5.1.6的依赖冲突

原因

react-scripts@5.0.1的peer依赖明确要求typescript版本为^3.2.1 || ^4,不支持5.x版本,所以你升级到typescript@5.1.6后出现了冲突。

解决办法

有三种可选方案:

  1. 降级typescript到4.x最新版
    安装兼容的typescript版本:
    npm install typescript@^4.9.5 --save-dev
    
  2. 使用--legacy-peer-deps跳过peer依赖检查
    执行更新或安装时加上该参数:
    npm install --legacy-peer-deps
    
    这个方法会忽略peer依赖冲突,但可能存在潜在兼容性问题,需测试项目是否正常运行。
  3. 更换构建工具
    如果想使用typescript 5.x,可以考虑替换react-scripts为Vite、Next.js等支持更高版本TS的构建工具,这类工具对新特性的支持更及时。

附用户提供的代码与错误信息

报错代码(使用createRoot):

import React from "react";
// import ReactDOM from "react-dom";
import { createRoot } from 'react-dom/client';
import App from "./components/App";

const container = document.getElementById('app');
const root = createRoot(container); // createRoot(container!) if you use TypeScript
root.render(<App tab="home" />);

正常运行代码(使用旧版render):

import React from "react";
import ReactDOM from "react-dom";
// import { createRoot } from 'react-dom/client';
import App from "./components/App";

// const container = document.getElementById('app');
// const root = createRoot(container); // createRoot(container!) if you use TypeScript
// root.render(<App tab="home" />);
ReactDOM.render(<App />, document.getElementById("root"));

依赖冲突错误信息:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: react-scripts@5.0.1
npm ERR! Found: typescript@5.1.6
npm ERR! node_modules/typescript
npm ERR!   dev typescript@"5.1.6" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm ERR! node_modules/react-scripts
npm ERR!   react-scripts@"5.0.1" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: typescript@4.9.5
npm ERR! node_modules/typescript
npm ERR!   peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm ERR!   node_modules/react-scripts
npm ERR!     react-scripts@"5.0.1" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:01:10