其他分享
首页 > 其他分享> > vue3与vite下,element-plus组件库怎么实现按需引入

vue3与vite下,element-plus组件库怎么实现按需引入

作者:互联网

vue3与vite下,element-plus组件库怎么实现按需引入

按需引入意义:减小打包后的包体积

全量引入

// main.js
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';

...

app.use(ElementPlus, { locale: zhCn });

手动按需引入

<template>
  <div class="app">
    <el-button>按钮</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
// 局部引入
import { ElButton } from 'element-plus'
import 'element-plus/theme-chalk/el-button.css'
import 'element-plus/theme-chalk/base.css'

export default defineComponent({
  components: { ElButton },
  setup() {
    return {}
  }
})
</script>
 
<style lang="less"></style>

自动按需引入同时设置国际化

  1. 安装依赖unplugin-auto-importunplugin-vue-components
yarn add unplugin-auto-import unplugin-vue-components -D
  1. 修改vite.config.js文件
import { defineConfig } from 'vite';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

export default defineConfig({
  ...
  plugins: [
    ...
    AutoImport({
      resolvers: [ElementPlusResolver({ importStyle: true })],
    }),
    Components({
      resolvers: [ElementPlusResolver({ importStyle: true })],
    }),
  ],
});
  1. 入口文件App.vue设置国际化
<template>
  <ElConfigProvider :locale="locale">
    <router-view />
  </ElConfigProvider>
</template>

<script>
  import { defineComponent } from 'vue'
  import { ElConfigProvider } from 'element-plus'
  import zhCn from 'element-plus/lib/locale/lang/zh-cn'

  export default defineComponent({
    components: {
      ElConfigProvider,
    },
    setup() {
      return {
        locale: zhCn,
      }
    },
  })
</script>

<style lang="less"></style>

大功告成

标签:vue,element,unplugin,plus,vue3,import,vite
来源: https://www.cnblogs.com/sk-3/p/16697573.html