How to configure webpack in storybook to allow babel to import react components outside of project folder

Viewed 4248

I am able to run storybook and develop react components within the storybook project folder successfully. However, I am trying to move the folder that contains all my components up a level (to be a sibling of the storybook folder).

So that instead of a structure like this

storybook
├── components
│   ├── Foo.js
│   └── Bar.js
├── stories
│   ├── index.stories.js

I have a folder structure like this

my_example_project
├── my_components
│   ├── Foo.js
│   └── Bar.js
├── my_storybook
│   ├── ...

When I try to import a component into a story, however, I get the following error

ERROR in ../my_components/Bar.js 4:9
Module parse failed: Unexpected token (4:9)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| const Bar = () => {
>   return <div>I am a Bar</div>;
| };

I've tried configuring my webpack to parse the components folder by adding a webpack.config.js file to my storybooks .storybook folder that looks like this


const path = require('path');

// Export a function. Accept the base config as the only param.
module.exports = async ({ config, mode }) => {
  // Make whatever fine-grained changes you need

  config.module.rules.push({
      test: /\.(js|jsx)$/,
      exclude: [/bower_components/, /node_modules/, /styles/],
      loader: 'babel-loader',
      include: path.resolve(__dirname, '../my_components/*'),
      query: {
    presets: ['@babel/preset-react']
  }
});


  // Return the altered config
  return config;
};

However, I run into the same error. What am I doing wrong?

Here is a github link to the example of the full example project

2 Answers

I accomplished this by editing .storybook/main.js as following:

const webpack = require('webpack');
const path = require('path');

module.exports = {
  stories: [
    '../src/**/*.stories.js',
    '../../../packages/react-components/src/**/*.stories.js'
  ],
  addons: [
    '@storybook/addon-docs',
    '@storybook/addon-viewport'
  ],

  webpackFinal: async (config) => {
    // Ensure shared component stories are transpiled.
    config.module.rules[0].include.push(
      path.resolve('../../packages/react-components/src')
    );

    return config;
  }
};
Related