Skip to content

摇树(Treeshaking)

作为一个组件框架,Vuetify 总是水平增长。根据您的项目,要求可能是打包体积尽量小。

自动摇树

摇树(Treeshaking)使你可以通过只包含使用的组件,从而显著地降低打包大小。Vuetify 使用插件来实现 Webpack 或者vite

安装 webpack-plugin-vuetify 或者 vite-plugin-vuetify 并在打包配置中启用它。注意 Vuetify 插件需要在 Vue 插件后,否则有可能工作不正常。

js
import vue from "@vitejs/plugin-vue";
import vuetify from "vite-plugin-vuetify";

export default {
  plugins: [vue(), vuetify()],
};
js
const { VueLoaderPlugin } = require("vue-loader");
const { VuetifyPlugin } = require("webpack-plugin-vuetify");

module.exports = {
  plugins: [new VueLoaderPlugin(), new VuetifyPlugin()],
};
js
const { VuetifyPlugin } = require("webpack-plugin-vuetify");

module.exports = {
  plugins: [new VuetifyPlugin()],
};

::: tab Nuxt

Nuxt 也使用 vite 插件,但需要一些额外配置才能以正确顺序加载:

js
import vuetify from "vite-plugin-vuetify";

export default defineNuxtConfig({
  modules: [
    async (options, nuxt) => {
      nuxt.hooks.hook("vite:extendConfig", (config) =>
        config.plugins.push(vuetify())
      );
    },
  ],
});

就是这样!无论在哪里使用,Vuetify 组件和指令都会被自动地导入到您的应用中。如果您在之前使用了通配符来导入,现在就可以移除掉它们。

diff
  import 'vuetify/styles'
  import { createVuetify } from 'vuetify'
- import * as components from 'vuetify/components'
- import * as directives from 'vuetify/directives'

手动导入

不使用加载器插件时,可手动导入组件。

js
import { createApp } from "vue";
import { createVuetify } from "vuetify";
import { VCard } from "vuetify/components/VCard";
import { VRating } from "vuetify/components/VRating";
import { VToolbar } from "vuetify/components/VToolbar";
import { Ripple } from "vuetify/directives";

const vuetify = createVuetify({
  components: {
    VCard,
    VRating,
    VToolbar,
  },
  directives: {
    Ripple,
  },
});

export default vuetify;

您还可以在 .vue 文件中就地导入组件,如下所示。

html
<template>
  <v-card>
    <v-card-title>...</v-card-title>
    <v-card-text>...</v-card-text>
  </v-card>
</template>

<script setup>
  import { VCard, VCardText, VCardTitle } from "vuetify/components/VCard";
</script>

局限性

使用加载器插件时,有几种情况需要手动导入组件。

动态组件

当使用动态组件时,插件无法解析正在呈现哪些静态组件。这通常发生在使用 built-in Vue <component>。关于动态组件的更多信息可以在 Vue 官方文档中找到 documentation

使用<component>的动态组件可以在本地注册:

html
<template>
  <component :is="button ? 'v-btn' : 'v-chip'" />
</template>

<script setup>
  import { VBtn } from "vuetify/components/VBtn";
  import { VChip } from "vuetify/components/VChip";
  import { shallowRef } from "vue";

  const btn = shallowRef(false);
</script>

分组件导入

所有组件都可以在vuetify/componentsvuetify/components/<group>中找到。但是,首选使用后者,因为它只加载所需的文件。如果你使用vuetify/components, Treeshaking 仍然可以在生产环境中工作,但是在开发过程中,即使你不使用组件,它也会因为加载样式而导致性能下降。