How to dynamically import custom package with storybook?

Member

by mac , in category: Javascript , a month ago

How to dynamically import custom package with storybook?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , a month ago

@mac 

To dynamically import a custom package with Storybook, you can follow these steps:

  1. Create a new story file for your custom package in the .storybook directory. For example, if your custom package is called my-package, create a new file called my-package.stories.js.
  2. In the story file, import the package dynamically using import() syntax. For example:
1
2
3
4
5
6
import React from 'react';
import { storiesOf } from '@storybook/react';
const MyPackage = React.lazy(() => import('my-package'));

storiesOf('MyPackage', module)
  .add('Default', () => <MyPackage />);


  1. Update your Storybook configuration to enable dynamic imports. In your .storybook/main.js file, add the following configuration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
module.exports = {
  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  typescript: {
    reactDocgen: 'react-docgen-typescript',
  },
  // Add webpack config to enable dynamic imports
  webpackFinal: async (config) => {
    config.module.rules.push({
      test: /.(ts|tsx|js|jsx)$/,
      loader: require.resolve('babel-loader'),
      options: {
        presets: ['@babel/preset-react', '@babel/preset-typescript'],
      },
    });

    return config;
  },
};


  1. Restart your Storybook server to apply the changes. Your custom package should now be dynamically imported in your Storybook stories.


Note: Make sure to replace my-package with the actual name of your custom package in the import statement. Additionally, ensure that your custom package is properly installed in your project's node_modules directory.