鉴于 antd 官方文档 对使用 babel-plugin-import
描述不够清楚,故写此文记录具体配置步骤。
1、npm run eject
在项目根路径下打开命令行,运行
npm run eject
如果使用了git,请确保执行此命令前没有未提交的内容
运行完毕后项目路径下会多出config
和scripts
文件夹,此外package.json
的内容也会发生改变,其中包括新增的babel
节点。
2、修改 package.json 配置
为package.json
中的babel
节点添加plugins
子节点,具体如下
{
// ...
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"style": "css"
}
]
]
}
}
再次启动项目,此时无需在代码中引入antd/dist/antd.css
,按钮也可正常显示
import React, { Component } from "react";
import { Button } from "antd";
// 配置了按需加载就不需要了
// import "antd/dist/antd.css";
class AntdDemo extends Component {
render() {
return (
<div>
<Button type="primary">
Button
</Button>
</div>
);
}
}
export default AntdDemo;