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

NextJS + Storybook可选链语法失效,构建失败求解决方案

解决Webpack 4不支持可选链导致Storybook构建失败的问题

问题背景

某个底层库使用了可选链语法

rehype-ignore 的 index.js 代码如下:

import { visit } from 'unist-util-visit';
const rehypeIgnore = (options = {}) => {
    const { openDelimiter = 'rehype:ignore:start', closeDelimiter = 'rehype:ignore:end' } = options;
    return (tree) => {
        visit(tree, (node, index, parent) => {
            if (node.type === 'element' || node.type === 'root') {
                // const start = node.children.findIndex((item) => item.type === 'comment' && item.value === openDelimiter);
                // const end = node.children.findIndex((item) => item.type === 'comment' && item.value === closeDelimiter);
                // if (start > -1 && end > -1) {
                //   node.children = node.children.filter((_, idx) => idx < start || idx > end);
                // }
                let start = false;
                node.children = node.children.filter((item) => {
                    if (item.type === 'raw' || item.type === 'comment') {
                        let str = item.value?.trim();
                        str = str.replace(/^<!--(.*?)-->/, '$1');
                        if (str === openDelimiter) {
                            start = true;
                            return false;
                        }
                        if (str === closeDelimiter) {
                            start = false;
                            return false;
                        }
                    }
                    return !start;
                });
            }
        });
    };
};
export default rehypeIgnore;
//# sourceMappingURL=index.js.map

近期运行Storybook时出现构建失败错误,package.json中Storybook相关配置未做任何修改。我并未直接使用rehype-ignore,它是项目的间接依赖。问题根源是Webpack 4原生不支持ES2020的可选链语法(?.),而rehype-ignore的代码中用到了该语法。之前尝试过Stack Overflow及GitHub上的方案但未解决,需要具体的Webpack配置优化指导。


解决方案

方案一:配置Babel转译间接依赖

Storybook默认不会转译第三方依赖,我们需要修改Webpack配置,让Babel处理rehype-ignore包:

  1. 打开项目根目录下的.storybook/main.js(若使用旧版Storybook,文件可能是.storybook/webpack.config.js)
  2. 添加以下配置:
module.exports = {
  webpackFinal: async (config) => {
    // 定位到已有的babel-loader规则
    const babelRule = config.module.rules.find(rule => 
      rule.test?.test('.js') && Array.isArray(rule.use)
    );

    if (babelRule) {
      // 将rehype-ignore加入需要转译的依赖列表
      babelRule.include.push(require.resolve('rehype-ignore'));
    }

    return config;
  },
};

方案二:升级Webpack到5(可选)

如果项目依赖允许,将Storybook的Webpack版本升级到5,Webpack 5原生支持可选链等ES2020语法,无需额外转译。但升级可能引发其他依赖兼容问题,需提前做好测试。

验证配置

修改完成后,重启Storybook验证:

npm run storybook

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:05:19