ekj*_*039 4 svg npm vue.js vuetify.js material-design-icons
我在我的 vue 项目中使用了materialdesignicons。
require ('../node_modules/@mdi/font/css/materialdesignicons.min.css);
Vue.use(Vuetify, {iconfont:'mdi'});
Run Code Online (Sandbox Code Playgroud)
我有一些动态创建的图标:
<v-icon>{{ some-mdi-file }}</v-icon>
Run Code Online (Sandbox Code Playgroud)
当我通过 (npm run build) 构建生产时,出现以下错误:
asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
img/materialdesignicons-webfont.someHash.svg (3.77 MiB)
Run Code Online (Sandbox Code Playgroud)
该文件大小很大,因为它包含每个图标,无论是否正在使用。有没有办法通过仅打包所使用的特定图标来缩小文件大小。我应该使用不同的包吗?警告:该项目是离线托管的,因此我需要将字体直接包含在我的项目中。
我查看了 vue-material-design-icons,但看起来它可能不适用于动态图标名称,并且它没有说明整体文件大小/性能。
我也看过这里,但单击“尺寸警告”链接会将我带到一个页面,其中 Vue 部分未填写 https://dev.materialdesignicons.com/getting-started/webfont
我建议使用@mdi/js包,它为每个图标提供 SVG 路径并支持树摇动。目前 Vuetify 不支持 SVG 图标,但将来应该会支持。
现在,创建自定义图标组件很容易:
<template>
<svg :class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path :d="path" />
</svg>
</template>
<script>
export default {
name: 'my-icon',
data: () => ({
path: '',
}),
methods: {
updatePath() {
if (!this.$scopedSlots) return
if (typeof this.$scopedSlots.default !== 'function') return
this.path = this.$scopedSlots
.default()
.map((n) => n.text)
.join('')
},
},
mounted() {
this.updatePath()
},
updated() {
this.updatePath()
},
}
</script>
<style scoped>
.icon {
display: block;
color: inherit;
fill: currentColor;
width: 24px;
height: 24px;
}
<style>
Run Code Online (Sandbox Code Playgroud)
然后要使用它,您只需导入您的组件和您想要使用的图标:
<template>
<div class="app">
<my-icon>{{mdiCheck}}</my-icon>
</div>
</template>
<script>
import MyIcon from 'path/to/my/icon.vue'
import { mdiCheck } from '@mdi/js'
export default {
name: 'my-app',
components: {
MyIcon,
}
data: () => ({
mdiCheck,
}),
}
</script>
Run Code Online (Sandbox Code Playgroud)