Storybook webpack 绝对导入

Edv*_*ski 7 javascript build reactjs webpack storybook

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

文件夹结构

我们正在使用 webpack 来构建和开发应用程序,它工作正常,有以下选项:

  resolve: {
    modules: [
      'node_modules',
      path.resolve('src')
    ]
  },
Run Code Online (Sandbox Code Playgroud)

我正在整合 storybook,发现在这个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
Run Code Online (Sandbox Code Playgroud)

对于下一行: import Button from 'react/components/Button';

作为标记:我将解析/模块添加到 .storybook/webpack 配置,并且如果我尝试导入其他任何内容,例如services/xxx- 它可以工作。

sun*_*eol 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;
  },
};
Run Code Online (Sandbox Code Playgroud)
  1. 根据(1)更改故事书代码
// Button.stories.jsx
import Button from 'view/components/Button';

//...
Run Code Online (Sandbox Code Playgroud)