Storybook webpack 绝对路径导入

11
在我们的应用程序中,我们使用绝对路径来导入模块。我们将react文件夹放置在我们的解析根目录中:

文件夹结构

我们使用webpack进行构建和开发应用程序,并且它可以正常工作,具有以下选项:
  resolve: {
    modules: [
      'node_modules',
      path.resolve('src')
    ]
  },

我正在处理storybook和found的集成问题,发现它无法找到这个react文件夹中的任何模块。

ERROR in ./stories/index.stories.js
Module not found: Error: Can't resolve 'react/components/Button' in 'project_name/stories'
 @ ./stories/index.stories.js

下一行的代码:

import Button from 'react/components/Button';

作为标记:我在.storybook/webpack配置中添加了resolve/modules,如果我尝试从其他地方导入任何东西,例如services/xxx - 它可以工作。

1个回答

1

问题

  • react 文件夹名称与实际 React 包位置冲突:node_modules/react。如果路径中不存在该文件,则 Webpack 尝试解析为 .resolution(默认为 node_modules)。
  • .resolution 不适用于此类用法,它主要用于包解析,因为它无法识别源字符串。
  • 要选择性更改路径,请使用 别名(alias)

解决办法

  1. 更改组件文件夹的名称,以避免与 node_modules/react 冲突。例如一个好的例子是 view/components/Button
  2. .storybook/main.js 中添加别名设置。
// .storybook/main.js
const path = require('path');

module.exports = {
  /* ... other settings goes here ... */

  /**
   * @param {import('webpack').Configuration} config
   *  */
  webpackFinal: async (config, { configType }) => {
    if (!config.resolve) config.resolve = {};
    // this config allows to resolve `view/...` as `src/view/...`
    config.resolve.alias = {
      ...(config.resolve.alias || {}),
      view: path.resolve(__dirname, '../src/view'),
    };
    return config;
  },
};
  1. 根据(1)修改storybook代码
// Button.stories.jsx
import Button from 'view/components/Button';

//...

我没有将我的代码放在src文件夹内。 - Shamoon
@Shamoon,.storybook/main.js 是否存在于除 src 以外的文件夹中? - sungryeol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接