使用Eject方式在 create-react-app 中使用 Ant Design of React

Ant Design 官网对 如何 react-app-rewired 的方式进行按需加载进行了说明,详见 在 create-react-app 中使用 一文,文中有这样一段话

你也可以使用 create-react-app 提供的 yarn run eject 命令将所有内建的配置暴露出来。不过这种配置方式需要你自行探索,不在本文讨论范围内。

本文主要就Eject方式进行探索

使用create-react-app创建项目

参考:如何扩展 Create React App 的 Webpack 配置 的Eject方式

首先使用create-react-app创建一个项目

$ create-react-app antd-test
复制代码

创建完项目后,进入项目目录,执行 yarn run eject 或 npm run eject

$ npm run eject
复制代码

执行后会出现提示,该操作不可逆,选择y继续

成功eject后会暴露webpack的配置,package.json增加了很多的依赖

安装antd

使用 cnpm 安装 antd

$ cnpm install antd
复制代码

修改src/App.js ,引入 antd 的按钮组件。

import React, { Component } from 'react';
import Button from 'antd/lib/button';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Button type="primary">Button</Button>
      </div>
    );
  }
}

export default App;
复制代码

执行npm install 安装依赖,并启动项目

$ cnpm install
$ npm start
复制代码

启动之后发现button并没有样式,需要引入antd的css文件

修改 src/App.css,在文件顶部引入 antd/dist/antd.css

@import '~antd/dist/antd.css';

.App {
  text-align: center;
}

...
复制代码

使用 babel-plugin-import 按需引入 antd 样式

在文件顶部引入 antd/dist/antd.css实际上加载了全部的 antd 组件的样式(对前端性能是个隐患)。 babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件(原理

$ cnpm install babel-plugin-import --save-dev
复制代码

修改src/App.js

...
- import Button from 'antd/lib/button';
+ import { Button } from 'antd';
...
复制代码

然后移除前面在 src/App.css 里全量添加的 @import '~antd/dist/antd.css';

此时发现按钮样式不生效了,最简单的方式是修改package.json文件里的babel配置, 增加babel-plugin-import的配置

...
  "babel": {
    "presets": [
      "react-app"
-    ]
+    ],
+   "plugins": [
+      ["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }]
+    ]
  }
...
复制代码

重新执行npm start,样式重新生效

至此使用Eject方式按需引入antd的方式已经探索完毕。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值