PS:也不只在react中用,其他框架也可,生态圈不一样配置会不同,但是能提供整体的思路,可以参考。
在批量引入之前,我们需要安装一个包并配置到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,可点击链接查看
PS:这样的好处:就是我们不需要一遍遍的引入和导出,手动一遍遍编写不同图标多组件,只需要引入一次icon 组件然后给不同的name就可以显示不通的图标,可维护性强。随着项目迭代过多,大量的需要图标时,不用再在需要引入图标的组件中占用较多的位置,也不用再后期图标更改时,全局搜索图标组件进行更改。