使用react-aspect-ratio依赖时无法解析react/jsx-runtime的问题
解决react-aspect-ratio升级后找不到react/jsx-runtime的问题
问题背景
将react-aspect-ratio从^1.0.50升级到^1.1.4后,执行生产构建命令时触发错误:
$ export NODE_OPTIONS=--max_old_space_size=4096 && NODE_ENV=production react-scripts build && webpack --config webpack.server.js Creating an optimized production build... Failed to compile. ./node_modules/react-aspect-ratio/dist/es/react-15.6.js Cannot find module: 'react/jsx-runtime'. Make sure this package is installed. You can install this package by running: yarn add react/jsx-runtime.
尝试执行yarn add react/jsx-runtime时安装失败,报错仓库不存在:
yarn add react/jsx-runtime yarn add v1.22.19 [1/5] Validating package.json... [2/5] Resolving packages... error Command failed. Exit code: 128 Command: git Arguments: ls-remote --tags --heads ssh://git@github.com/react/jsx-runtime.git Directory: /home/rajesh/work/projects/p/shopdrop-web Output: ERROR: Repository not found. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
核心原因
react/jsx-runtime不是独立的npm包,它是React 17及以上版本内置的模块,用于新的JSX自动转换逻辑。新版本react-aspect-ratio依赖了React 17+的这一特性,但你的项目要么React版本低于17,要么构建工具未适配新的JSX转换规则。
解决方案
方案1:升级React到17.x及以上版本
执行命令升级React和ReactDOM:
yarn add react@^17.0.0 react-dom@^17.0.0 # 或使用npm npm install react@^17.0.0 react-dom@^17.0.0
如果用Create React App,需同步升级react-scripts到4.x及以上版本(CRA 4才支持React 17的JSX转换):
yarn add react-scripts@^4.0.0
方案2:降级react-aspect-ratio到兼容旧版React的版本
若不想升级React,可回退到之前能正常运行的版本:
yarn add react-aspect-ratio@^1.0.50 # 或使用npm npm install react-aspect-ratio@^1.0.50
方案3:手动配置构建工具适配JSX转换(非CRA项目)
如果是自定义webpack配置,修改babel配置启用JSX自动转换:
在.babelrc或babel.config.json中添加:
{ "presets": [ ["@babel/preset-react", { "runtime": "automatic" }] ] }
同时确保已安装@babel/preset-react:
yarn add @babel/preset-react --dev
内容的提问来源于stack exchange,提问作者user352290
相关产品推荐
相关产品推荐

