【问题标题】:Storybook with absolute paths带有绝对路径的故事书
【发布时间】:2019-01-17 03:48:21
【问题描述】:

在我们的应用程序中,我们使用绝对路径进行导入。例如,如果我们有一个相对于src 文件夹的路径,我们可以只写import module from "components/myComponent"。

问题是这在故事书中不起作用。经过一番挖掘,你可以使用默认的 webpack 配置并根据需要扩展它,如文档 here 中所示。我基于此的思考过程是像这样简单地将我的src 目录推送到模块数组上,

module.exports = (baseConfig, env, defaultConfig) => {
    // Extend defaultConfig as you need.
    defaultConfig.resolve.modules.push("src");

    return defaultConfig;
};

但是,在这样做之后,我在尝试运行故事书时最终收到以下错误。

./node_modules/@storybook/addon-knobs/src/react/index.js 中的错误 模块解析失败:意外令牌 (26:9) 您可能需要一个 适当的加载器来处理这种文件类型。 |常量初始内容 = getStory(上下文); | const props = { 上下文,storyFn:getStory,频道,knobStore,initialContent }; |返回 ; | }; |

真的不知道从这里去哪里。

【问题讨论】:

    标签: javascript reactjs webpack storybook


    【解决方案1】:

    我在使用 CLI 后遇到了这个问题,我可以通过将 .storybook/main.js 修改为:

    const path = require('path');
    
    module.exports = {
      ...other settings....,
    
      webpackFinal: async (config) => {
        config.resolve.modules = [
          ...(config.resolve.modules || []),
          path.resolve(__dirname, "../src"),
        ];
    
        return config;
      },
    
    }
    

    请注意,我正在使用 Typescript 和 ReactJS,并且我的 Typescript 文件的基本 URL 设置为 src。那就是我的 tsconfig 有这个:

    {
    ...,
     "baseUrl": "./src/",
    }
    

    【讨论】:

    • 是否还应该像在批准的答案中那样包含“node_modules”?
    • 他不需要,因为他在那里传播 Storybook 模块,其中已经有 node_modules
    【解决方案2】:

    这看起来与这个 GitHub 问题 https://github.com/storybooks/storybook/issues/2704 非常相似,其中建议的修复是在 webpack 配置中使 src 目录成为绝对目录。

    module.exports = {
      //...
      resolve: {
        modules: [path.resolve(__dirname, 'src'), 'node_modules']
      }
    };
    

    【讨论】:

      【解决方案3】:

      我尝试了其他解决方案,但没有帮助。所以我使用了一个 webpack 插件来解决这个问题。

      按照此处的说明操作后:https://storybook.js.org/docs/riot/configure/webpack#extending-storybooks-webpack-config

      我使用的是 TypeScript 版本,我已将 webpackFinal 字段更改为如下:

      // main.ts
      import { TsconfigPathsPlugin } from 'tsconfig-paths-webpack-plugin';
      import type { Configuration } from 'webpack';
      
      export default {
        // ... other fields
        webpackFinal: async (config: Configuration) => {
          if (!config.resolve) {
            config.resolve = {};
          }
      
          config.resolve.plugins = [
            ...(config.resolve.plugins || []),
            new TsconfigPathsPlugin(),
          ];
      
          return config;
        },
      };
      

      【讨论】:

        猜你喜欢
        • 2019-08-28
        • 2022-01-06
        • 2021-02-11
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 1970-01-01
        • 2020-09-13
        • 2020-12-07
        相关资源
        最近更新 更多