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

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.0
  • next: ^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:

  1. 在next.config.js中添加配置:
/** @type {import('next').NextConfig} */
const nextConfig = {
  compiler: {
    emotion: true,
  },
};

module.exports = nextConfig;
  1. 卸载不再需要的Babel插件:
npm uninstall @emotion/babel-plugin

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 13:45:15