Storybook webpack absolute import
Asked Answered
B

1

11

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.

Bloodstream answered 17/3, 2019 at 13:40 Comment(0)
M
1

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';

//...
Meningitis answered 27/7, 2022 at 6:15 Comment(2)
I don't have my code in srcUnseat
@Unseat does.storybook/main.js exist in a folder other than src?Meningitis

© 2022 - 2024 — McMap. All rights reserved.