Vue:离线使用材料设计图标/大小

时间:2019-02-08 14:31:06

标签: vue.js svg npm vuetify.js material-design-icons

我在vue项目中使用materialdesignicons。

require ('../node_modules/@mdi/font/css/materialdesignicons.min.css);
Vue.use(Vuetify, {iconfont:'mdi'});

我有一些动态创建的图标:

 <v-icon>{{ some-mdi-file }}</v-icon>

当我通过(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)

该文件的大小很大,因为它包含每个图标,无论是否使用它。有没有一种方法可以通过仅打包使用的特定图标来缩小该文件的大小。我应该使用其他包装吗?警告:该项目是离线托管的,因此我需要将字体直接包含在我的项目中。

我查看了vue-material-design-icons,但它似乎不适用于动态图标名称,并且没有说明文件的整体大小/性能。

我也看过这里,但单击“尺寸警告”链接将我带到未填写Vue部分的页面 https://dev.materialdesignicons.com/getting-started/webfont

1 个答案:

答案 0 :(得分:0)

我建议为此使用@mdi/js软件包,该软件包为每个图标提供SVG路径并支持树摇动。目前,Vuetify不支持SVG图标,但支持it should in the future

就目前而言,创建自定义图标组件非常简单:

<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>

然后使用它,只需导入组件和要使用的图标:

<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>