react批量引入svg圖標(biāo)的方法
在批量引入之前,我們需要安裝一個(gè)包并配置到typescript.json文件中。
1. 安裝:
yarn add -D @type/webpack-env
2. 配置typescript.json
"compilerOptions": {
"types": ["@types/webpack-env"]
}批量引入處理并導(dǎo)出封裝組件
在src文件下新建一個(gè)icon文件,然后新建一個(gè).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 = []
}
/**
*
* 導(dǎo)出圖標(biāo)
*
*/
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
}使用方式:
// 引入圖標(biāo)
import { IconFont } from '@/icons/sider_left_icon'
<IconFont
name='library'
width="23"
className={styles.library_button_icon}
/>注:我之所以能直接使用@去默認(rèn)引入src下的所有文件,是因?yàn)槲以趖ypescript中配置path
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
},
"types": ["@types/webpack-env"]
},詳細(xì)了解@types/webpack-env,可點(diǎn)擊鏈接查看
到此這篇關(guān)于react批量引入svg圖標(biāo)的文章就介紹到這了,更多相關(guān)react批量引入svg內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React Router V5:使用HOC組件實(shí)現(xiàn)路由攔截功能
這篇文章主要介紹了React Router V5:使用HOC組件實(shí)現(xiàn)路由攔截功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03
React中的路由嵌套和手動(dòng)實(shí)現(xiàn)路由跳轉(zhuǎn)的方式詳解
這篇文章主要介紹了React中的路由嵌套和手動(dòng)實(shí)現(xiàn)路由跳轉(zhuǎn)的方式,手動(dòng)路由的跳轉(zhuǎn),主要是通過Link或者NavLink進(jìn)行跳轉(zhuǎn)的,實(shí)際上我們也可以通JavaScript代碼進(jìn)行跳轉(zhuǎn),需要的朋友可以參考下2022-11-11
React中完整實(shí)例講解Recoil狀態(tài)管理庫(kù)的使用
這篇文章主要介紹了React中Recoil狀態(tài)管理庫(kù)的使用,Recoil的產(chǎn)生源于Facebook內(nèi)部一個(gè)可視化數(shù)據(jù)分析相關(guān)的應(yīng)用,在使用React的實(shí)現(xiàn)的過程中,因?yàn)楝F(xiàn)有狀態(tài)管理工具不能很好的滿足應(yīng)用的需求,因此催生出了Recoil,對(duì)Recoil感興趣可以參考下文2023-05-05
詳解超簡(jiǎn)單的react服務(wù)器渲染(ssr)入坑指南
這篇文章主要介紹了詳解超簡(jiǎn)單的react服務(wù)器渲染(ssr)入坑指南,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02
React官方團(tuán)隊(duì)完善原生Hook閉包陷阱
這篇文章主要為大家介紹了React官方團(tuán)隊(duì)出手,補(bǔ)齊原生Hook短板閉包陷阱的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07

