目前element plus还在快速迭代阶段(更新日志),配置不同版本有不小改动,本节主要记录vue3+vite2+elment plus(v2.2)按需引入+国际化配置,在按需自动导入以及国际化这块踩了大坑,搞了一下午,有任何bug应时刻关注官方社区问题汇总
通常来讲做实际项目时候我们都应该组件按需导入,这能大大降低项目打包后的代码,同时显著提高单页首页加载速度,elment plus提供了新的按需加载方式——按需自动导入,和传统手动按需导入不同,这里我们需要安装unplugin-vue-components 和 unplugin-auto-import这两款插件
1 | npm install -D unplugin-vue-components unplugin-auto-import |
然后把下列代码插入到你的Vite中即可,main.js上无需再添加任何element plus相关代码,连同css都是按需导入加载的,甚至ElMessage这类组件都可以直接使用,简直美丽极了,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // vite.config.ts 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()], }), Components({ resolvers: [ElementPlusResolver()], }), ], }) // main.ts import 'element-plus/dist/index.css' |
按需加载后,官方也给我们提供了新的国家化方式ConfigProvider,我们直接将el-config-provider标签套在项目App.vue根节点即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <template> <el-config-provider :locale="locale"> <app /> </el-config-provider> </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> |
问题来了,官方上面配置在dev本地开发没问题,一旦进行vite打包就挂了直接报错,并且错误并非必现,有时候能打包通过,但打包好的包语言包依然没生效,错误信息如下:
1 | 'default' is not exported by node_modules/element-plus/lib/locale/lang/zh-cn.js, imported by src/App.vue |
报错原因是官方语言包文件导出方式错误,我们可以把包拿到后修改一份出来自己管理,通过element-plus/es/locale/lang/zh-cn目录直接找到相关的js,它应该是下面的样子
1 2 3 4 5 6 7 8 9 10 | // App.vue <template> <el-config-provider :locale="zhCn"> <router-view></router-view> </el-config-provider> </template> <script setup lang="ts"> import zhCn from "/utils/zh-cn"; </script> |
由于element plus在快速迭代中,这个错误应该很快会被修复,新的东西总是有坑需要人填,因此大家在实际公司项目开发时候无需过多过于追求新技术,否则很多时候出现问题网上很难找到资料自己坑了自己
下一篇:npm升级package.json中所有依赖包到最新版本
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"vue3+vite2+elment plus按需自动引入+国际化配置"
最新评论