具有绝对路径的故事书

时间:2018-08-09 15:39:30

标签: javascript reactjs webpack storybook

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

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

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)您可能需要一个   适当的加载程序来处理此文件类型。 | const initialContent   = getStory(context); | const props = {上下文,storyFn:getStory,channel,stantStore,initialContent}; |回报; | }; |

真的不确定从这里要去哪里。

3 个答案:

答案 0 :(得分:2)

使用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/",
}

答案 1 :(得分:1)

这与GitHub问题https://github.com/storybooks/storybook/issues/2704非常相似,其中建议的修复方法是使src目录在您的Webpack配置中绝对存在。

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

答案 2 :(得分:0)

我尝试了其他解决方案,但没有帮助。所以我在我的案例中使用了一个 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;
  },
};
相关问题