React 之antd

本文介绍了如何在create-react-app环境下配置并使用antd库,包括安装初始化、按需引入和国际化设置。通过customize-cra和babel-plugin-import,实现按需加载antd组件,减少应用体积。

React 之antd

参考网站:https://ant.design/docs/react/use-with-create-react-app-cn

create-react-app 是业界最优秀的 React 应用开发工具之一。在 create-react-app 创建的工程中使用 antd 组件,并自定义 webpack 的配置以满足各类工程化需求。

1.安装和初始化

$ npm i yarn 					##安装yarn
$ yarn create react-app demo 	##文件名:demo;自动初始化一个脚手架并安装 React 项目的各种必要依赖
$ cd antd-demo  				##进入项目
$ yarn start   					##启动项目此时浏览器会访问 http://localhost:3000/ ,看到 Welcome to React 的界面

2.引入antd

$ yarn add antd					 ## 安装并引入 antd
$ npm i antd -S					 ## 安装并引入 antd

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

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

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

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

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

.App {
  text-align: center;
}

3.按需引入配置

1).使用customize-cra

$ yarn add react-app-rewired customize-cra 				  ## 安装 customize-cra

更改package.json

"scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test",
+   "test": "react-app-rewired test",
}

在项目根目录创建一个 config-overrides.js 用于修改默认配置。

module.exports = function override(config, env) {
  // do stuff with the webpack config...
  return config;
};

2).使用 babel-plugin-import

$ yarn add babel-plugin-import

修改 config-overrides.js

+ const { override, fixBabelImports } = require('customize-cra');

//- module.exports = function override(config, env) {
//-   // do stuff with the webpack config...
//-   return config;
//- };
+ module.exports = override(
+   fixBabelImports('import', {
+     libraryName: 'antd',
+     libraryDirectory: 'es',
+     style: 'css',
+   }),
+ );

移除前面在 src/App.css 里全量添加的 @import '~antd/dist/antd.css'; 样式代码,并且按下面的格式引入模块。

 // src/App.js
  import React, { Component } from 'react';
//- import Button from 'antd/es/button';
+ import { Button } from 'antd';
  import './App.css';

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

4.国际化

import { LocaleProvider } from 'antd'
import zhCN from 'antd/es/locale-provider/zh_CN';

render(
    // 国际化-- locale={zhCN} 汉语
    <LocaleProvider locale={zhCN}>
        <App />
    </LocaleProvider>,
    document.querySelector('#root')
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值