快捷搜索: 王者荣耀 脱发

关于react脚手架使用antd进行按需加载操作

一、当我们使用antd时,首先使用,来下载antd UI组件库

yarn add antd
//若是使用antd-mobile  则下载antd-mobile

二、使用antd组件库的全局引入,做一个Button按钮

import React from react
import ReactDOM from react-dom

import {
          
   Button} from antd
//这个是引入antd的全局样式,将antd的样式全部引入进来,会引入很多多余的样式,浪费性能
//所以我们需要对antd进行按需加入,就可以不写这行代码了,就可以需要
import antd/dist/antd.css;

ReactDOM.render(
    <Button type=primary>Hello</Button>,
    document.getElementById(root)
)

三、通过antd按需加载来实现按需引入,来实现Button按钮

1、下载三个依赖

yarn add babel-plugin-import
yarn add  customize-cra
yarn add react-app-rewired//下载这个依赖时,可能会出现bug报错,因为使用这个命令,会默认下载最新的版本,而最新的版本可能会不稳定
yarn add react-app-rewired@2.0.2-next.0    //所以我使用的是这个版本

2、在项目的根目录下建立一个文件夹 config-overrides.js

//config-overrides.js


//按需打包
const {
          
   
	override, 
	fixBabelImports,
} = require(customize-cra)

//根据项目中的【import】语句打包,也就是说项目import了谁就打包谁,比如我只import Button组件,就可以只打包Button相关样式
//这里的import使用的是babel-plugin-import依赖,将前缀省略去了,这个依赖需要手动安装,然后会在package.json文件中有体现
module.exports = override(
    fixBabelImports(import, {
          
   
        libraryName: antd,//若是为antd-mobile进行配置,则改为antd-mobile
        libraryDirectory: es,
        style: css,//自动打包相关样式
    }),
);

3、在package.json文件中修改配置

"scripts": {
          
   
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
替换为

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

react-app-rewired命令会加载config-overrides.js文件来进行扩展配置。注意eject并没有换成react-scripts eject脚本。

上面就配置完了,重启项目会发现,antd的样式已经生效了。并且项目中的样式文件是按需引入的不会全部引入。

四、自定义antd主题/使用less样式文件

react默认是不识别less文件的,如果不进行配置,直接使用less文件,其中的样式是不生效的 1、安装第三方依赖

yarn add less-loader@5.0.0//默认安装最新的版本时,可能会出现报错  TypeError: this.getOptions is not a function
yarn add less

2、对 三 中的配置进行了修改

const {
          
   
	override, 
	fixBabelImports, 
	addLessLoader  //使用less样式文件
} = require(customize-cra);

module.exports = override(
    fixBabelImports(import,{
          
   
        libraryName: antd,
        libraryDirectory: es,
        style: true,  //将导入css更改为less
    }),
    addLessLoader({
          
   
        javascriptEnabled: true,
        modifyVars: {
          
   @primary-color: #1DA57A},
    }),
);
经验分享 程序员 微信小程序 职场和发展