如何按需导入 Ant design 以使用进行解构的组件?
How to import Ant design on demand to work with components which does destructuring?
我在我的 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。我做错了什么?
需要这样导入import Tabs from "antd/lib/tabs";
。
Ant design 文档提到:
antd supports tree shaking of ES modules, so using import { Button } from 'antd';
would drop js code you didn't
use.(https://ant.design/docs/react/getting-started#Import-on-Demand).
此外,如果您使用的是 create-react-app 和 Ant Design 版本 4,您可能希望按需加载 CSS。为此,请按照下列步骤操作:
- 安装 craco (craco installation guide)
- 安装 babel-plugin-import (documentation to install)
- 在根目录下创建一个craco.config.js文件(看craco安装指南)
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"
}
我在我的 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。我做错了什么?
需要这样导入import Tabs from "antd/lib/tabs";
。
Ant design 文档提到:
antd supports tree shaking of ES modules, so using
import { Button } from 'antd';
would drop js code you didn't use.(https://ant.design/docs/react/getting-started#Import-on-Demand).
此外,如果您使用的是 create-react-app 和 Ant Design 版本 4,您可能希望按需加载 CSS。为此,请按照下列步骤操作:
- 安装 craco (craco installation guide)
- 安装 babel-plugin-import (documentation to install)
- 在根目录下创建一个craco.config.js文件(看craco安装指南)
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"
}