简体   繁体   中英

Storybook webpack absolute import

In our app we are using absolute paths for import modules. We have react folder into our resolve root:

Folder structure

We are using webpack for build and develop app and it works ok, with the next options:

  resolve: {
    modules: [
      'node_modules',
      path.resolve('src')
    ]
  },

I'm working on integration of storybook and found, that it can't find any module from this react folder.

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

for the next line: import Button from 'react/components/Button';

As mark: I added resolve/modules to.storybook/webpack config and also if I try to import anything other from, for example services/xxx - it works.

Issues

  • react folder name conflicts with actual React package location: node_modules/react . Webpack tries to resolve to .resolution (default is node_modules ) if the file does not exist in the path.
  • .resolution is not appropriate for this sort of usage. it is mostly used for package resolution because it can't tell source strings.
  • to change path selectively, use alias instead .

Solution

  1. change your component folder's name so that it does not collide with node_modules/react . a good example is view/components/Button .
  2. add alias to .storybook/main.js setting
// .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. change storybook code in accordance with (1)
// Button.stories.jsx
import Button from 'view/components/Button';

//...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM