如何在Storybook 8 + NextJS/SWC中启用实验性装饰器
解决Storybook 8 + NextJS中实验性类装饰器构建崩溃问题
问题分析
你遇到的Expression expected错误源于SWC默认不支持旧版实验性类装饰器,而Storybook 8的@storybook/nextjs集成当前已默认启用SWC(与文档描述存在版本迭代后的行为差异)。你之前配置的swc函数未生效,大概率是配置结构或优先级问题导致。
解决方案
1. 修正Storybook的SWC配置
Storybook 8的@storybook/nextjs中,需确保swc配置函数的参数与返回值结构正确,尝试替换main.ts中的配置为:
import type { StorybookConfig } from '@storybook/nextjs'; const config: StorybookConfig = { framework: '@storybook/nextjs', // 保留你的其他配置项 swc: (existingConfig) => { return { ...existingConfig, jsc: { ...existingConfig.jsc, parser: { ...existingConfig.jsc?.parser, decorators: true, // 若你的装饰器写在类export前(如@Decorator class Demo),需加此配置 decoratorsBeforeExport: true, }, }, }; }, }; export default config;
2. 同步TypeScript配置
在项目根目录的tsconfig.json中,启用实验性装饰器相关选项:
{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true // 若项目依赖装饰器元数据则开启 } }
3. 通过NextJS配置传递SWC规则(备选方案)
若上述配置仍未生效,可通过NextJS的配置文件传递SWC选项,同时让Storybook复用该配置:
- 在
main.ts中指定NextJS配置路径:
const config: StorybookConfig = { framework: { name: '@storybook/nextjs', options: { nextConfigPath: './next.config.js', }, }, // 其他配置项 };
- 在
next.config.js中添加SWC装饰器支持:
/** @type {import('next').NextConfig} */ const nextConfig = { swcMinify: true, compiler: { swc: { jsc: { parser: { decorators: true, decoratorsBeforeExport: true, }, }, }, }, }; module.exports = nextConfig;
4. 验证配置是否生效
可在swc函数中添加日志输出,确认配置逻辑是否执行:
swc: (existingConfig) => { console.log('SWC配置已触发:', existingConfig); // 其余配置代码 }
启动Storybook时查看控制台,若能看到该日志,说明配置函数已正常执行。
关键注意点
- Storybook 8的
@storybook/nextjs集成已默认启用SWC,文档描述未及时更新,属于版本迭代后的正常行为。 - 旧版实验性装饰器需根据写法决定是否同时开启
decoratorsBeforeExport: true。 - 确保TypeScript配置与SWC配置一致,避免编译规则冲突。
内容的提问来源于stack exchange,提问作者olivierr91
相关产品推荐
相关产品推荐

