在整合element-plus的时候,自动导入模块与引用到这两个插件的简单介绍,详情见官网:unplugin-vue-components和unplugin-auto-import
在使用过程中
- 安装
npm install -D unplugin-vue-components unplugin-auto-import
结合官方文档,在详细说一下具体的使用心得(以vite为例)
vite
// 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: [
vue(),
AutoImport({
// 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
imports: ['vue', 'vue-router', 'vue-i18n'],
include: [
/\.[tj]sx?$/,
/\.vue$/,
/\.vue\?vue/,
],
resolvers: [
// 自动导入 Element Plus 相关函数,如:ElMessage, ElMessageBox... (带样式)
ElementPlusResolver(),
// 自动导入图标组件
IconsResolver({})
],
vueTemplate: true, // 是否在 vue 模板中自动导入
dts: path.resolve(pathSrc, 'types', 'auto-imports.d.ts') // (false) 配置文件生成位置,默认是根目录 /auto-imports.d.ts
}),
Components({
include: [
/\.[tj]sx?$/,
/\.vue$/,
/\.vue\?vue/,
],
// 只要项目中,在components目录下的文件,会自动导入到components.d.ts中,这样,页面或者组件中就不用再次引入了,也无需在`main.js`通过app.component全局注册了
dirs: ['src/components', 'src/**/components',],
extensions: ['vue', 'jsx', 'tsx', 'ts', 'js'],
resolvers: [
// 自动注册图标组件
IconsResolver({
enabledCollections: ['ep'] //@iconify-json/ep 是 Element Plus 的图标库
}),
// 自动导入 Element Plus 组件
ElementPlusResolver()
],
dts: path.resolve(pathSrc, 'types', 'components.d.ts') // (false) 配置文件生成位置,默认是根目录 /components.d.ts
}),
})
然后项目启动之后,就会在types目录下生成两个文件
效果
<script lang="ts" setup>
// 当前行也可以省略不写
import { getCurrentInstance, ref } from 'vue'
// 无需再次引入,可以省略当前行代码
const {proxy} = getCurrentInstance()
import PasswordForm from './components/passwordForm.vue'
....
效果如图
但是这里面会有eslint的提示,官方这么解释的
💡 When using TypeScript, we recommend to disable no-undef rule directly as TypeScript already check for them and you don’t need to worry about this.
eslint的解决
解决方案一(官方解决方案)
AutoImport({
eslintrc: {
enabled: true, // 会在项目根目录自动生成.eslintrc-auto-import.json
},
})
在.eslintrc.js
的extends里面添加一行代码
extends: [
'.eslintrc-auto-import.json',
],
解决方案二
所以在.eslintrc.js
的rules里面添加一行代码,全局有效。。
'no-undef': 'off', // 组件使用autoImport,eslint 就不用检测了
eslint提示就消失了
element-plus 动态路由,样式文件的懒加载问题的处理
在用动态路由的时候,因为动态路由的页面,是在项目启动后,通过调用后台接口,来动态import加载文件的。所以如果按照上述配置会造成如下的问题
很多在异步加载的页面里面引用到的组件,会在自己定义的scss文件之后加载,这样就会导致自己写的样式,无法达到覆盖element-ui自带样式的效果。
解决方案:
- 样式文件在全局引入。
main.ts文件引入文件如下图
2. ElementPlusResolver配置调整
3.
最后达到效果: