如何使樱桃采摘反应组件库(如lodash&日期/fns [英] How to make cherry picking react component library like lodash & date/fns

查看:93
本文介绍了如何使樱桃采摘反应组件库(如lodash&日期/fns的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个小型图书馆,其中包含20-25个不同的组件,制作了一个npm软件包.

I have made one small library which includes 20-25 different components & made an npm package of it.

我的React项目(我想在其中使用这些组件)有很多页面[路由]进行了延迟加载,因此每个页面都有自己的捆绑包.

my react project, where I want to use these components, has many pages[routes] used lazy-loading so each page has its own bundle.

但是当我在首页[App.js]上写语句时.

but when I write the statement on my home page[App.js].

    import { MyModal } from 'my-react-lib';

每个组件都被加载到主页包中.所以我的初始加载性能最差. [2Mb的初始捆绑包大小]

each and every component is loaded into home page bundle. so my initial loading performance is worst. [2Mb initial bundle size]

我已经阅读了摇树的概念,并尝试在webpack& amp;中实施事件即使使用汇总功能,但它们只能生成bundle.js,而不能满足我的要求.

I have read the concept of tree shaking and event tried to implement in webpack & even with rollup but they only make bundle.js but not as per mine requirement.

我愿意实现进出口之类的樱桃采摘.与date-fns&罗达斯做到了.

I am willing to achieve cherry-picking like import-export. same as date-fns & lodash does.

      import format from 'date-fns/format';
      import debounce from 'lodash/debounce';

如何实现?

   import MyModal from 'my-react-lib/MyModal';
   import OtherComponent from 'my-react-lib/OtherComponent';

推荐答案

通过汇总,您可以将库拆分成几个独立的块.您必须提供一个对象,将名称映射到入口点,并映射到汇总配置的 input 属性.看起来像这样:

Rollup allows you to split your library into several independent chunks. You have to provide an object, mapping names to entry points, to the input property of the rollup configuration. It looks like this:

input: {
    index: 'src/index.js',
    theme: 'src/Theme',
    badge: 'src/components/Badge',
    contentCard: 'src/components/ContentCard',
    card: 'src/elements/Card',
    icon: 'src/elements/Icon',
    ...

src/index.js看起来像这样:

export { default as Theme } from './Theme'
export { default as Badge } from './components/Badge'
...

请查看汇总文档: https://rollupjs.org/guide/zh-CN#输入

输出设置为目录:

output: [
  {
    dir: 'dist/es',
    format: 'es',
  },
],

然后您在package.json中声明入口点,如下所示:

Then you declare the entry point in your package.json as follows:

"module": "dist/es/index.js",

然后可以导入您的库中的模块:

The modules of your library can then be imported:

import { Theme, Badge } from 'your-component-library'

这篇关于如何使樱桃采摘反应组件库(如lodash&日期/fns的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆