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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 11:06:18