【问题标题】:Is it possible to tree-shake module imports in live-served storybook?是否可以在实时故事书中对模块导入进行摇树?
【发布时间】:2020-04-10 23:01:41
【问题描述】:

我在我的项目中使用带有 CRA preset 的 Storybook 并在本地运行 Storybook。我想在我的故事书中使用命名空间导入以获得更好的开发者体验:

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

它似乎在构建过程中正确地摇树 - 两种方法产生相同的包大小。

但是,当通过 yarn storybook 在本地运行故事书时,从聚合命名空间导入:

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

导致构建时间增加大约 20 秒。

我尝试使用 material ui guide 中的两个 tree-shaking 插件和 projectRoot/.storybook.babelrc.js 中的建议配置,但没有运气。

它肯定会处理.babelrc.js,因为那里的无效语法会破坏构建。但是它仍然会加载所有图标。

是否有可能让它在 CRA 中工作?

【问题讨论】:

  • 在同一个链接中似乎有一节介绍如何让它与 CRA 一起工作
  • 据我了解,这适用于您想要在 CRA 构建中进行 tree-shake,而不是 Storybook。它说“如果你正在使用 Create React App,你将需要使用几个项目来让你使用 .babelrc 配置,而不会弹出。”。但 Storybook 似乎用它的自定义 .babelrc.js 文件为我解决了这个问题。
  • 另外,我看不出修改yarn start 脚本以使用react-app-rewired 会如何影响运行yarn storybook的结果

标签: reactjs create-react-app storybook tree-shaking


【解决方案1】:

你只需要结合Material-UI: Minimizing Bundle SizeStorybook: Configure Babel的指南。


安装 babel-plugin-import 后。

yarn add -D babel-plugin-import

.storybook/main.js 上,您必须将这 2 个 babel 插件配置添加到 storybook babel 插件中。

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;
  },
};

在尝试运行 storybook 之后,你可能会遇到这样的错误。

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

你必须改变

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

进入

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

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 2019-10-20
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    相关资源
    最近更新 更多