从Babel迁移至Next.js 13 SWC时遭遇React压缩错误#130
解决Next.js 13移除
.babelrc后使用SWC出现React错误#130的问题 你遇到的问题确实和styled-components以及inline-react-svg的Babel插件未被SWC替代配置有关。React错误#130是组件类型无效的报错,本质是SWC没有处理原来Babel插件负责的编译逻辑,导致渲染了非有效React组件的内容。
解决方案步骤:
1. 用SWC内置配置替代babel-plugin-styled-components
Next.js 13+提供了SWC原生支持styled-components,无需Babel插件,只需在next.config.js中添加如下配置:
/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { styledComponents: { // 对应原来babel-plugin-styled-components的配置 ssr: true, displayName: true, preprocess: false, }, }, }; module.exports = nextConfig;
2. 替换inline-react-svg的SWC兼容方案
SWC没有直接对应的inline-react-svg插件,需要用@svgr/webpack替代,步骤如下:
- 安装依赖:
npm install @svgr/webpack --save-dev
- 在
next.config.js的webpack配置中添加SVG处理规则:
/** @type {import('next').NextConfig} */ const nextConfig = { // 保留上面的styled-components配置 compiler: { styledComponents: { ssr: true, displayName: true, preprocess: false, }, }, webpack(config) { // 添加SVG转React组件的规则 config.module.rules.push({ test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: ['@svgr/webpack'], }); return config; }, }; module.exports = nextConfig;
3. 移除.babelrc文件
完成上述配置后,删除.babelrc,重启Next.js开发服务即可。
错误原因说明
原来的.babelrc中,babel-plugin-styled-components负责将styled-components的模板语法编译为React可识别的组件,inline-react-svg负责将SVG文件转成React组件。移除.babelrc后,SWC默认不会处理这些逻辑,导致代码中出现未编译的无效组件,触发React错误#130。
内容的提问来源于stack exchange,提问作者Ted Vu
相关产品推荐
相关产品推荐

