【问题标题】:How to import Ant design on demand to work with components which does destructuring?如何按需导入 Ant 设计以使用进行解构的组件?
【发布时间】:2021-06-12 13:04:06
【问题描述】:

我在我的 create-react-app 项目中按需导入 antd 组件,例如 Collapse、Tabs、Select 等,它们会进行一些解构 如:

import { Tabs } from "antd/lib/tabs";
import 'antd/lib/tabs/style/css';
import { Collapse } from "antd/lib/collapse";
import 'antd/lib/collapse/style/css';
import { Select } from "antd/lib/select";
import 'antd/lib/select/style/css';

const { Panel } = Collapse;
const { TabPane } = Tabs;
const { Option } = Select;

我收到错误TypeError: Cannot destructure property 'Panel' of 'antd_lib_collapse__WEBPACK_IMPORTED_MODULE_3__.Collapse' as it is undefined.
我不想使用import { Collapse, Select } from "antd";,因为它带来了大量的javascript。我做错了什么?

【问题讨论】:

    标签: reactjs create-react-app antd destructuring


    【解决方案1】:

    需要以这种方式导入import Tabs from "antd/lib/tabs";

    【讨论】:

      【解决方案2】:

      Ant 设计文档提到:

      antd 支持 ES 模块的 tree shaking,所以使用 import { Button } from 'antd'; 会丢弃你没有的 js 代码 使用。(https://ant.design/docs/react/getting-started#Import-on-Demand)。

      此外,如果您使用 create-react-app 和 Ant Design 版本 4,您可能希望按需加载 CSS。要获得此信息,请按以下步骤操作:

      module.exports = {
          babel: {
              plugins: [['import', {
                  libraryName: 'antd',
                  libraryDirectory: 'es',
                  style: 'css',
              }]],
          },
      };
      • 最后,在 package.json 文件的脚本部分更新对 react-scripts 的现有调用以使用 craco CLI:

      /* package.json */
      
      "scripts": {
      -   "start": "react-scripts start",
      +   "start": "craco start",
      -   "build": "react-scripts build",
      +   "build": "craco build"
      -   "test": "react-scripts test",
      +   "test": "craco test"
      }

      参考:https://programmersought.com/article/95268781523/

      【讨论】:

        猜你喜欢
        • 2020-10-06
        • 2019-01-11
        • 1970-01-01
        • 2023-04-07
        • 2019-10-06
        • 1970-01-01
        • 2021-11-02
        • 2019-01-22
        • 2018-08-04
        相关资源
        最近更新 更多