react+webpack+antd框架自定义使用阿里iconfont图标。
时间: 2024-01-16 15:03:00 浏览: 40
步骤如下:
1. 在阿里iconfont官网上选择所需图标,添加到购物车中,并下载对应的图标字体文件。
2. 将字体文件复制到项目中的一个合适的目录下,比如 `src/assets/fonts`。
3. 在项目中安装 `@iconify/react` 和 `@iconify/icons` 包,用于渲染图标。
```
npm install @iconify/react @iconify/icons --save
```
4. 在 `webpack.config.js` 文件中配置字体文件的加载器,以及 `less-loader` 和 `css-loader` 的配置。
```
const IconfontWebpackPlugin = require('iconfont-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts'
}
}
]
},
{
test: /\.less$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'less-loader',
options: {
lessOptions: {
modifyVars: {
'hack': `true;@import "${require.resolve('antd/lib/style/color/colorPalette.less')}";`,
'icon-font-path': '"../assets/fonts/iconfont"'
}
}
}
}
]
}
]
},
plugins: [
new IconfontWebpackPlugin({
resolve: {
extensions: ['.tsx']
}
})
]
};
```
其中,`IconfontWebpackPlugin` 是用于自动将 `@iconify/icons` 中的图标转换成 React 组件,并导出到指定目录的插件。
5. 在代码中使用图标:
```
import { Icon } from '@iconify/react';
import userIcon from '@iconify/icons-ant-design/user';
const MyComponent = () => {
return (
<div>
<Icon icon={userIcon} />
</div>
);
};
```
其中,`userIcon` 是从 `@iconify/icons-ant-design` 包中导入的,可以替换成其他需要使用的图标。`Icon` 组件会自动根据图标名称找到对应的字体文件,并渲染出图标。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)