Vite+Storybook+React+TS项目中Emotion样式报错求助
解决Storybook + Vite + Emotion组件选择器编译错误
问题现象
启动Storybook时弹出错误提示:
Component selectors can only be used in conjunction with @emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware compiler transform.
尝试改用@emotion/styled/macro导入时,出现语法错误:missing ) after argument list。
核心原因
主Vite配置中已配置Emotion的Babel编译插件,但Storybook的Vite构建环境未同步该配置,导致Emotion的组件选择器(如样式代码中的${Dot})无法被正确解析编译。
解决方案
修改Storybook的main.js文件,在viteFinal方法中为React插件补充Emotion相关配置:
const svgr = require('vite-plugin-svgr'); module.exports = { stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'], addons: [ '@storybook/addon-links', '@storybook/addon-essentials', '@storybook/addon-interactions', 'storybook-addon-swc', ], framework: '@storybook/react', core: { builder: '@storybook/builder-vite', }, typescript: { reactDocgen: 'react-docgen', }, async viteFinal(config, { configType }) { // 找到已有的React插件并更新Emotion配置 const reactPlugin = config.plugins.find(plugin => plugin.name === 'vite:react'); if (reactPlugin) { reactPlugin.options.jsxImportSource = '@emotion/react'; reactPlugin.options.babel = { plugins: ['@emotion/babel-plugin'], }; } config.plugins = [...config.plugins, svgr()]; return config; }, features: { storyStoreV7: true, }, };
补充说明
- 无需切换到
@emotion/styled/macro,保持原有的import styled from '@emotion/styled'导入方式即可。 - 确保项目已安装必备依赖:
npm install @emotion/react @emotion/styled @emotion/babel-plugin --save
内容的提问来源于stack exchange,提问作者Юрий Петров
相关产品推荐
相关产品推荐

