使用Emotion时Rollup构建报错:'default'未导出的解决方案求助
解决Rollup构建@emotion组件时的'default'导出错误
看起来你遇到的是Rollup处理@emotion生态中CommonJS与ESM模块互操作时的导出映射问题。@emotion/memoize的CommonJS版本用module.exports = memoize直接导出,而依赖它的@emotion/is-prop-valid用ESM默认导入方式引入,Rollup的commonjs插件需要显式配置才能正确解析这种导出关系。
下面是具体的解决方案:
1. 修正Rollup的commonjs插件配置
修改你的rollup.config.js,调整commonjs插件的导出映射规则,同时优化resolve插件的扩展名配置,确保Rollup能正确识别@emotion的特殊文件格式:
import typescript from 'rollup-plugin-typescript2'; import pkg from './package.json'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; export default { input: 'src/index.ts', output: [ { file: pkg.main, format: 'cjs', exports: 'named' }, { file: pkg.module, format: 'es', compact: true } ], external: [...Object.keys(pkg.peerDependencies || {})], plugins: [ typescript({ typescript: require('typescript') }), resolve({ // 添加@emotion常用的文件扩展名,确保Rollup能正确解析模块 extensions: ['.ts', '.tsx', '.js', '.jsx', '.cjs.js', '.esm.js'] }), commonjs({ include: ['node_modules/**', '../../../node_modules/**'], namedExports: { // 告诉Rollup:@emotion/memoize的默认导出对应名为memoize的导出 '@emotion/memoize': ['memoize'] } }) ] };
2. 优化CustomButton组件(可选但推荐)
你当前把DefaultButton这个styled组件定义在类内部,会导致每次组件实例化时都重新创建这个样式组件,影响性能。建议把它移到类外部,只创建一次:
import React from 'react'; import CustomButtonProps from './custom-button-props'; import styled, { StyledComponent } from '@emotion/styled'; import { StyleConstants } from '@enterprise-api/constants'; // 移到类外部,全局仅初始化一次 const DefaultButton: StyledComponent<any, any, any> = styled.button` height: 2rem; padding-left: 0.75rem; padding-right: 0.75rem; ${StyleConstants.defaultButton} `; export class CustomButton extends React.PureComponent<CustomButtonProps> { public constructor(props: CustomButtonProps) { super(props); } public render(): React.ReactNode { if (this.props.style) { return ( <button style={this.props.style} onClick={this.props.onClick}> {this.props.text} </button> ); } return <DefaultButton onClick={this.props.onClick}>{this.props.text}</DefaultButton>; } } export default CustomButton;
为什么之前的配置无效?
你之前尝试的namedExports路径太具体(指向了dist下的具体文件),而Rollup的commonjs插件更推荐用包名配置导出映射,这样它能自动处理包的入口文件,避免路径匹配错误。另外,添加resolve插件的扩展名配置能确保Rollup正确识别@emotion的特殊文件后缀(比如.cjs.js和.esm.js)。
如果修改后仍有问题,可以尝试清除node_modules和Rollup缓存(rollup-plugin-typescript2会生成缓存,可删除node_modules/.cache/rollup-plugin-typescript2目录),再重新执行构建。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

