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

如何在Storybook与Next.js中使用绝对导入?配置后运行报错

Storybook模块解析错误解决方案

问题描述

我在.storybook/main.js中配置了如下webpackFinal:

webpackFinal: async (config) => {
    config.resolve.modules = [
      ...(config.resolve.modules || []),
      path.resolve(__dirname),
    ];

    return config;
  },

运行Storybook时出现模块解析错误:

resolve 'components/Common/Button' in '/myprojectpath/pages'
  Parsed request is a module
  using description file: /myprojectpath/package.json (relative path: ./pages)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      /myprojectpath/pages/node_modules doesn't exist or is not a directory
      looking for modules in /myprojectpath/node_modules

Next.js项目运行正常,但Storybook无法解析components/Common/Button这类路径。

问题原因

Next.js默认会将项目根目录加入webpack的模块解析路径列表,因此你可以直接用components/xxx这类根相对路径导入文件。但你当前的Storybook配置中,仅把.storybook目录(path.resolve(__dirname)指向的是.storybook文件夹)加入了解析路径,而你的components目录在项目根目录下,导致Storybook无法定位到目标模块。

解决方案

方案1:添加项目根目录到模块解析路径

修改webpackFinal配置,将项目根目录(.storybook的上级目录)加入resolve.modules:

const path = require('path');

module.exports = {
  // 其他Storybook配置...
  webpackFinal: async (config) => {
    config.resolve.modules = [
      ...(config.resolve.modules || []),
      path.resolve(__dirname, '../'),
    ];

    return config;
  },
};

方案2:配置路径别名(更直观)

直接通过resolve.alias映射components路径,明确指定模块位置:

const path = require('path');

module.exports = {
  // 其他Storybook配置...
  webpackFinal: async (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      'components': path.resolve(__dirname, '../components'),
    };

    return config;
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:36:33