记录vite2按需导入ui库组件和样式

716 阅读1分钟

介绍

相信大家已经了解了vite2Vue3,本文以element-plus为例,记录一下vite2按需导入ui库的组件和样式

安装插件依赖

npm i unplugin-vue-components -D
npm i vite-plugin-style-import -D

unplugin-vue-components 是由 Vue官方人员开发的一款自动引入插件,可以省去比如 UI 库和components的大量 import 语句。 vite-plugin-style-import按需导入组件库样式的插件。

配置vite.config.js

import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import {createStyleImportPlugin,ElementPlusResolve} from 'vite-plugin-style-import';

plugins: [
    vue(),
    vueJsx(),
    Components({  //组件按需引入
        resolvers: [ElementPlusResolver()],
    }),
    createStyleImportPlugin({
        resolvers: [ElementPlusResolve()],
    }),
],

国际化配置

element-plus官方提供了el-config-provider组件来进行语言的切换,在App.vue里面进行配置,

<template>
    <el-config-provider :locale="locale">
      <router-view />
    </el-config-provider>
</template>

<script setup>
import { ref } from 'vue'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
const locale = ref(zhCn)
</script>

使用

components/Demo.vue

<template>
  <div>测试{{ prop.data }}</div>
  <el-button @click="add">点我</el-button>
  <el-date-picker
      v-model="value"
      type="date"
      placeholder="Pick a day"
      :disabled-date="disabledDate"
      :shortcuts="shortcuts"
  />
</template>

<script lang="ts" setup>
  import { reactive,ref } from 'vue'
  const prop = defineProps({
    data: String
  })
  const emit = defineEmits(['change'])

  const value = ref('')
  const shortcuts = [
    {
      text: '今天',
      value: new Date(),
    },
    {
      text: '昨天',
      value: () => {
        const date = new Date()
        date.setTime(date.getTime() - 3600 * 1000 * 24)
        return date
      },
    },
    {
      text: '一周前',
      value: () => {
        const date = new Date()
        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
        return date
      },
    }
  ]
  const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
  }

  const add = () => {
    console.log(prop.data);
    emit('change', '1234')
  }

</script>

<style scoped lang="scss">

</style>

home.vue

<template>
  <div>{{page}}</div>
  <Demo data="数据" @change="change" />
</template>

<script setup>
  import { ref} from  'vue'
  const page = ref('home')
  const change = function (val){
    console.log(val)
  }
</script>

组件不再需要导入,直接使用即可。

特别注意

到这里已经基本完成了按需导入。如果使用ElMessage或者ElMessageBox等这类弹框组件时,样式是没有导入的,解决方法是在main.js导入弹框组件的样式。

import 'element-plus/es/components/message-box/style/index' //按需引入后,弹框样式需单独引入
import 'element-plus/es/components/message/style/index'

结束

因为弹框样式单独引入,# vite2打包出现警告“@charset“ must be the first rule in the file }@charset “UTF-8“,解决方法是:在vite.config.js里面,加一个sass的配置,把charset关掉就行了

css:{
    preprocessorOptions:{  //配置全局css
        scss:{
            charset: false
        }
    }
},