react批量引入svg图标的方法
更新时间:2024年03月12日 14:23:26 作者:#做一个清醒的人
这篇文章主要介绍了react批量引入svg图标的方法,在批量引入之前,我们需要安装一个包并配置到typescript.json文件中,需要的朋友可以参考下
在批量引入之前,我们需要安装一个包并配置到typescript.json文件中。
1. 安装:
yarn add -D @type/webpack-env
2. 配置typescript.json
"compilerOptions": {
"types": ["@types/webpack-env"]
}批量引入处理并导出封装组件
在src文件下新建一个icon文件,然后新建一个.tsx文件
注:这块代码可直接copy走
import Icon from '@ant-design/icons';
// 批量引入
const importAll = (requireContext: __WebpackModuleApi.RequireContext) => {
const requireAll = requireContext.keys().map(key => {
const name = key.replace(/\.\/(.*)\.\w+$/, '$1');
console.log(name, requireContext(key))
return { name, value: requireContext(key) };
})
return requireAll
}
let routeList: {name: string, value: string}[] = []
try {
routeList = importAll(require.context('../assets/icons', true, /\.svg$/))
} catch (error) {
console.log(error);
routeList = []
}
/**
*
* 导出图标
*
*/
const IconFont = (props: {name: string, width?: string | number, className?: string}) => {
const ListItem = routeList.find(item => item.name === props.name)
return (
<Icon
component={() => (
<img
src={ListItem?.value}
alt=""
width={props.width || 16}
/>
)}
{...props}
/>
);
};
export {
IconFont
}使用方式:
// 引入图标
import { IconFont } from '@/icons/sider_left_icon'
<IconFont
name='library'
width="23"
className={styles.library_button_icon}
/>注:我之所以能直接使用@去默认引入src下的所有文件,是因为我在typescript中配置path
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
},
"types": ["@types/webpack-env"]
},详细了解@types/webpack-env,可点击链接查看
到此这篇关于react批量引入svg图标的文章就介绍到这了,更多相关react批量引入svg内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
React Hooks - useContetx和useReducer的使用实例详解
这篇文章主要介绍了React Hooks - useContetx和useReducer的基本使用,本文通过实例代码给大家讲解的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-11-11
React无限滚动插件react-infinite-scroll-component的配置优化技巧
react-infinite-scroll-component是React无限滚动插件,简化滚动加载逻辑,支持自定义提示和触发距离,兼容移动端,体积小巧,适用于列表、聊天等场景,需结合虚拟滚动优化性能,本文介绍React无限滚动插件react-infinite-scroll-component的配置+优化,感兴趣的朋友一起看看吧2025-09-09


最新评论