基于React 18构建的库无法兼容React 19的问题求助
React 18/19 兼容的Node包构建后跨版本运行异常
编辑说明:如果您认为我的问题存在不足,欢迎在评论区告知原因😀。我认为这是其他开发者也可能遇到的有效问题,故保留此提问。
我正在基于vite v6 + React 18/19构建一个Node包,相关配置附于文末。目前遇到的核心问题:
- 用React 19构建的库,仅能在React 19项目中正常运行;
- 用React 18构建的库,仅能在React 18项目中正常运行,无法兼容React 19。
开发环境下,该库可在两个版本的React中正常运行,无兼容性问题;只有当作为npm包安装到其他项目时,才会出现异常。
我已将react和react-dom设置为外部依赖,且在安装该库的项目中验证过:库中导入的React对象与项目自身的React对象引用完全一致(React1 === React2),但仍出现以下错误:
错误详情
- React 19构建的库在其他项目中运行时报错:
Uncaught TypeError: ReactSharedInternals is undefined
- React 18构建的库在React 19项目中运行时报错:
undefined (reading 'ReactCurrentDispatcher')
配置文件
vite.config.ts
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from "path"; export default defineConfig({ plugins: [react()], build: { lib: { entry: path.resolve(__dirname, 'src/index.ts'), name: 'app', formats: ['es', 'umd', 'cjs'] }, rollupOptions: { external: [ 'react', 'react-dom', '@mui/material', ], }, sourcemap: false, minify: false } })
package.json
{ "name": "app", "version": "1.1.17", "type": "module", "main": "dist/app.umd.js", "module": "dist/app.es.js", "types": "dist/index.d.ts", "exports": { "import": "./dist/app.es.js", "require": "./dist/app.cjs.js" }, "scripts": { "dev": "vite", "build": "vite build && tsc -p tsconfig.build.json --declaration --emitDeclarationOnly --declarationDir dist", "lint": "eslint .", "preview": "vite preview" }, "files": [ "dist" ], "dependencies": { }, "devDependencies": { "@emotion/styled": "^11.13.5", "@eslint/js": "^9.15.0", "@mui/material": "^6.1.9", "@types/node": "^22.10.1", "@types/react": "^19.1.0", "@types/react-dom": "^18.3.1", "@vitejs/plugin-react-swc": "^3.8.1", "eslint": "^9.15.0", "eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-refresh": "^0.4.19", "globals": "^15.12.0", "react": "^19.0.0", "react-dom": "^19.0.0", "typescript": "~5.6.2", "typescript-eslint": "^8.15.0", "vite": "^6.2.5" }, "keywords": [ "react", "mui", "snackbar", "provider", "hook" ], "peerDependencies": { "@emotion/styled": "*", "@mui/material": "*", "react": ">=18.*.*", "react-dom": ">=18.*.*" }, "sideEffects": false }
内容的提问来源于stack exchange,提问作者Parsa_Gholipour
相关产品推荐
相关产品推荐

