2

I use Storybook with CRA preset in my project and run Storybook locally. I would like to use namespace imports in my storybook for better developer experience:

// this is more convenient
import { ArrowForward, Star } from '@material-ui/icons';

// than this
import ArrowForward from '@material-ui/icons/ArrowForward'
import Star from '@material-ui/icons/Star'

It seems to be tree-shaking correctly during the build process - both approaches yield the same bundle size.

However when running storybook locally via yarn storybook, importing from the aggregate namespace:

import { ArrowForward, Star } from '@material-ui/icons'

results in approximately 20 seconds longer build time.

I tried using both tree-shaking plugins from material ui guide with the suggested config inside projectRoot/.storybook.babelrc.js, but with no luck.

It sure processes the .babelrc.js, since invalid syntax there breaks the build. However it still loads all the icons.

Is it possible to get it working within a CRA?

Michal Kurz
  • 1,592
  • 13
  • 41
  • There seems to be a section about how to get it to work with CRA in that same link – Daniel Dec 18 '19 at 11:57
  • As far as I understand it, that's for when you want to tree-shake within CRA build, not Storybook. It says "If you are using Create React App, you will need to use a couple of projects that let you use .babelrc configuration, without ejecting.". But Storybook seems to solve that problem for me with its custom .babelrc.js file. – Michal Kurz Dec 18 '19 at 12:39
  • Also, I don't see how modifying the`yarn start` script to use the react-app-rewired would influence the result of running `yarn storybook` – Michal Kurz Dec 18 '19 at 12:41

1 Answers1

0

You just have to combine guide from Material-UI: Minimizing Bundle Size and Storybook: Configure Babel.


After install babel-plugin-import.

yarn add -D babel-plugin-import

On the .storybook/main.js you'll have to add these 2 babel plugin config into storybook babel plugin.

module.exports = {
  babel: async (options) => {
    options.plugins.push([
      'babel-plugin-import',
      {
        libraryName: '@material-ui/core',
        libraryDirectory: '',
        camel2DashComponentName: false,
      },
      'core',
    ]);
    options.plugins.push([
      'babel-plugin-import',
      {
        libraryName: '@material-ui/icons',
        libraryDirectory: '',
        camel2DashComponentName: false,
      },
      'icons',
    ]);

    return options;
  },
};

After it done after trying to run storybook, you might encounter error like this.

Module not found: Can't resolve '@material-ui/core/makeStyles' in '/your/project'

You will have to change

import { makeStyles } from '@material-ui/core';

into

import { makeStyles } from '@material-ui/core/styles';

pipeCh
  • 1
  • 2