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

使用Rollup打包styled-components时遇'isValidElementType'导出错误

解决Rollup打包styled-components时'isValidElementType'未导出的问题

我之前也碰到过这个一模一样的问题,本质是react-is采用CommonJS格式导出,而Rollup的commonjs插件默认没能正确识别它的命名导出映射,加上styled-components内部依赖这个模块,咱们可以通过以下步骤解决:

步骤1:确保依赖安装完整

首先确认你的项目里已经安装了react-is,因为styled-components会依赖它来做类型校验。如果还没装,执行下面的命令:

npm install react-is --save
# 或者用yarn
yarn add react-is

步骤2:修改Rollup配置文件

你需要对rollup.config.js做两处调整:

  • 把react-is添加到external数组中(和react、react-proptypes一样,作为外部依赖不打包进bundle)
  • 给commonjs插件添加namedExports配置,明确指定react-is的导出映射

修改后的完整配置如下:

import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'cjs'
  },
  external: [ 'react', 'react-proptypes', 'react-is' ], // 新增react-is
  plugins: [
    resolve({ extensions: [ '.js', '.json', '.jsx' ] }),
    commonjs({
      include: 'node_modules/**',
      // 新增namedExports配置,映射react-is的导出
      namedExports: {
        'react-is': [ 'isValidElementType' ]
      }
    }),
    babel({ exclude: 'node_modules/**' })
    // ... 其他插件
  ]
}

为什么这样能解决?

  • 添加react-is到external:避免把这个第三方依赖打包进你的bundle,让它在运行时从外部获取(和react一样)
  • 配置namedExports:因为react-is的CommonJS导出里,isValidElementType是挂在module.exports上的属性,但Rollup默认没法自动识别这种非标准的ES模块导出,所以我们手动告诉它这个模块的命名导出有哪些。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:23:11