Next.js构建报错:unhandledrejection TypeError: 无法读取__emotion_real属性
解决Next.js + Emotion构建时的
Cannot read properties of undefined (reading '__emotion_real')错误 问题背景
更新Next.js到14.0.3及Emotion相关库后,生产构建阶段触发以下错误:
unhandledRejection TypeError: Cannot read properties of undefined (reading '__emotion_real') at createStyled (C:\Projects\travel11\travel-frontend\node_modules\@emotion\styled\base\dist\emotion-styled-base.cjs.prod.js:97:20) at C:\Projects\travel11\travel-frontend\.next\server\chunks\837.js:38:144700 { type: 'TypeError' }
涉及核心库版本:
@emotion/babel-plugin: ^11.10.6@emotion/react: ^11.11.1@emotion/styled: ^11.11.0next: ^14.0.3
解决方案
1. 对齐Emotion全量包版本
不同版本的Emotion子包可能存在兼容冲突,统一所有Emotion相关包的版本:
npm install @emotion/react@11.11.1 @emotion/styled@11.11.1 @emotion/babel-plugin@11.11.1
2. 修正Babel配置
调整.babelrc.js,确保React自动导入的运行时正确指向Emotion,同时明确插件参数:
module.exports = { presets: [ [ 'next/babel', { 'preset-react': { runtime: 'automatic', importSource: '@emotion/react', }, }, ], ], plugins: [ ['@emotion/babel-plugin', { sourceMap: false }], 'babel-plugin-macros' ], };
3. 配置TypeScript支持(若使用TS)
在tsconfig.json中添加Emotion的JSX导入源,确保类型和运行时匹配:
{ "compilerOptions": { "jsxImportSource": "@emotion/react" } }
4. 清理缓存后重建
删除Next.js缓存、依赖包和锁文件,重新安装后构建:
# Windows rd /s /q .next node_modules package-lock.json # macOS/Linux rm -rf .next node_modules package-lock.json npm install npm run build
5. 改用Next.js SWC编译器(备选方案)
如果自定义Babel配置仍有问题,可以移除.babelrc.js,改用Next.js内置的SWC支持Emotion:
- 在
next.config.js中添加配置:
/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { emotion: true, }, }; module.exports = nextConfig;
- 卸载不再需要的Babel插件:
npm uninstall @emotion/babel-plugin
内容的提问来源于stack exchange,提问作者Maxim Shkividorov
相关产品推荐
相关产品推荐

