Closed xmasuhai closed 3 years ago
vue ? 你可以使用 transformAssetUrls, 目前除了使用 vite 没有支持, 其他都支持。推荐使用 vue-cli 插件
谢谢
Here is my Icon
component with vite import.meta.globEager
(or lazy import with import.meta.glob
)
(code is written with vue-jsx, vue-jss, and typescript)
import { VueSvgIcon } from '@yzfe/vue3-svgicon';
import { computed, defineComponent, Ref, toRefs } from 'vue';
import { useTheme } from 'vue-jss';
import { Theme } from '@/constants/theme';
// import all svg file under svg-icon
// NOTE: folder name must be svg-icon, and the files would pass to svgicon loader (defined in vite.config)
const modules = import.meta.globEager('./svg-icon/*.svg');
const Icon = defineComponent({
name: 'Icon',
props: { icon: String, color: { type: String, default: '#000' }, size: { type: Number, default: 24 } },
setup(props) {
// @ts-expect-error: vue-jss suck
const theme: Ref<Theme> = useTheme<Theme>();
const { icon, color, size } = toRefs(props);
const iconData = computed(() => modules[`./svg-icon/${icon.value}.svg`]?.default);
const processedColor = computed(() => theme.value.palette[color.value]?.main ?? color.value);
return () => <VueSvgIcon data={iconData.value} width={size.value} color={processedColor.value} />;
},
});
export default Icon;
and the usage
<Icon icon="close" size={24} color="primary" />
<Icon icon="arrow-left" size={24} color="#f00" />
每次导入都需要写明具体的路径
import arrowData from 'svgfilepath/arrow.svg'
,不方便 封装一个属性名来直接提供给组件 像这样使用:<my-icon name="icon-down"/>
,路径只需写例如./src/assets/icons
,而不是./src/assets/icons/icon-down.svg