Module parse失败:_templateObject已声明,Emotion与Next.js兼容问题求助
解决Emotion styled导致的"Identifier '_templateObject' has already been declared"编译错误
问题场景
项目原本运行完全正常,无代码改动、未更换Node.js版本的情况下,突然触发编译错误:Module parse failed: Identifier '_templateObject' has already been declared。尝试完全卸载重装Node.js无效,在线IDE中项目可正常运行,移除Emotion的CSS-in-JS代码后编译恢复正常。
报错日志如下:
ready - started server on 0.0.0.0:3000, url: http://localhost:3000 info - Loaded env from C:\Users\user\Downloads\zigi-ui-master\.env event - compiled client and server successfully in 631 ms (203 modules) wait - compiling /_error (client and server)... event - compiled client and server successfully in 93 ms (204 modules) warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works wait - compiling /... error - ./pages/index.jsx Module parse failed: Identifier '_templateObject' has already been declared (13:9) File was processed with these loaders: * ./node_modules/next/dist/compiled/@next/react-refresh-utils/dist/loader.js * ./node_modules/next/dist/build/webpack/loaders/next-swc-loader.js You may need an additional loader to handle the result of these loaders. | return data; | } > function _templateObject() { | var data = _tagged_template_literal([ | "\n text-align: center;\n justify-content: center;\n"
原因分析
这个错误本质是Emotion的CSS-in-JS转译与Next.js默认的SWC编译器冲突,在处理模板字面量时重复生成了_templateObject标识符。大概率是本地依赖缓存损坏、SWC编译缓存异常,或是Emotion与Next.js版本间的隐性兼容性问题被触发。
解决方案
1. 清理本地缓存与依赖
- 删除本地依赖文件夹:
Windows:rmdir /s /q node_modules
macOS/Linux:rm -rf node_modules - 删除锁文件:
rm package-lock.json(npm)或rm yarn.lock(yarn) - 重新安装依赖:
npm install或yarn install - 清理Next.js编译缓存:手动删除
.next文件夹,或执行npm run build --clean
2. 明确配置Emotion的SWC支持
在next.config.js中开启Emotion的SWC编译支持,避免转译冲突:
/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { emotion: true, }, } module.exports = nextConfig
3. 更新Emotion到兼容版本
执行命令更新@emotion/react和@emotion/styled,确保与当前Next.js版本匹配:
npm update @emotion/react @emotion/styled
内容的提问来源于stack exchange,提问作者Netty
相关产品推荐
相关产品推荐

