React项目中对iconFont的封装
Published: 2023-02-16 10:15:00

##在React项目中引入iconFont

1. 引入
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bkncsg4ndbau8y2ndcia.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q5qut8qnyo1p546gl0ef.png)
2.使用
```javascript
 <svg className={Style.icon} aria-hidden="true">
    <use xlinkHref={`#icon-Company`}></use>
 </svg>

style 
.icon {
  width: 1em; 
  height: 1em;
  vertical-align: -0.15em;//垂直外边距
  fill: currentColor;//填充颜色
  overflow: hidden;//超出部分隐藏
}

```
3.效果

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcvc4ns9751hk9yh9f1u.png)
##封装
1. 基本参数

######（样式的权重由高到低）
- iconName icon的name
- fontSize icon的大小
- color  icon的样式
- style  icon的style样式
- className icon的类
```javascript
 import { CSSProperties } from 'react'
import { iconNameType } from '../../static/iconfont/iconNameType'
import Style from './index.module.scss'
 interface Props{
    fontSize?:number,
    className?:string,
    style?:CSSProperties,
    iconName:iconNameType
    color?:string
 }
   const Icon = (props:Props) => {
    const {fontSize,className,style,iconName,color}=props
    const wrapperStyle={...style,fontSize:fontSize+'px',color}
    return (
        <div className={className} style={wrapperStyle}>
          <svg className={Style.icon} aria-hidden="true">
            <use xlinkHref={`#icon-${iconName}`}></use>
          </svg>
        </div>
    )
}
export default Icon
```
2. 使用
```javascript
    <Icon
    iconName='Company'
    color='#008000c1'
    fontSize={40}
    ></Icon>
```
3. 效果

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fjvtv4ycajjmfc9hy5er.png)

## 设置iconName的数据类型
> 这里的iconName的值必须使用iconfont.js中的id。因此需要读取到iconfont.js所有的id，并拼接成 字符串字面量类型

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ukakn4pnx5zxdv7um1bw.png)

1. 预计效果 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qgm2ix52vnslun4kpny6.png)
2. 实现
思路 使用node.js的fs 读取文件，并写入到到当前文件夹generateIconType.js
```javascript
const fs =require('fs')
const fileName='./iconfont.js'
const iconNameTypePath ="./iconNameType.ts"
const readFile=(filePathName)=>{
    fs.readFile(filePathName,'utf-8',(error,data)=>{
        if (error) {
            throw error
        }
    //获取所有id="icon-Company"格式的正则
     const reg=/id="[a-zA-Z-]*"/g
    //id="icon-Company需要被替换正则
      const searchValueReg=/(id="icon-)|"/g 
    //   map(item=>item.replaceAll(searchValueReg,""))
    const idMatchArrs=  data.match(reg)
   const idArrs= idMatchArrs.map(item=>{
   const replactItem= item.replaceAll(searchValueReg,"")
   return `"${replactItem}"`
})
   const iconNameType=idArrs.join("|")
   console.log('====================================');
   console.log(iconNameType);
   console.log('====================================');
   fs.writeFile(iconNameTypePath,
    `export type iconNameType=${iconNameType}`,
    'utf8',(err)=>{
        if (err) {
            console.log('====================================');
            console.log("write",err);
            console.log('====================================');
        }

   })
    })
}
function generateIconType(){
    readFile(fileName)
}
generateIconType()
```
3. 结果

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/752g0qdrd7262v8na1vr.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qmvpmhjpt8u021j0bbm8.png)