Vite相关插件
记录下日常使用 Vite 的一些相关插件。
unplugin-auto-import
自动导入 vue3 相关方法,支持vue
, vue-router
, vue-i18n
, @vueuse/head
, @vueuse/core
等自动引入
效果
// 引入前
import { ref, computed } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
//引入后
const count = ref(0)
const doubled = computed(() => count.value * 2)
// 引入前
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <div>{count}</div>
}
//引入后
export function Counter() {
const [count, setCount] = useState(0)
return <div>{count}</div>
}
安装
npm i -D unplugin-auto-import
vite.config.jsjavascript
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({
imports: ['vue', 'vue-router', 'vue-i18n', '@vueuse/head', '@vueuse/core'],
dts: 'src/auto-import.d.ts',
// 可以选择auto-import.d.ts生成的位置(默认根目录),建议设置为'src/auto-import.d.ts'
}),
],
})
原理: 自动生成 auto-imports.d.ts 文件用于代码提示,如下
auto-imports.d.tstypescript
// Generated by 'unplugin-auto-import'
// We suggest you to commit this file into source control
declare global {
const ref: (typeof import('vue'))['ref']
const reactive: (typeof import('vue'))['reactive']
const computed: (typeof import('vue'))['computed']
const createApp: (typeof import('vue'))['createApp']
const watch: (typeof import('vue'))['watch']
const customRef: (typeof import('vue'))['customRef']
const defineAsyncComponent: (typeof import('vue'))['defineAsyncComponent']
}
export {}
注意:由于没有局部导入,在代码跳转查看时,就会跳转到 auto-imports.d.ts 文件,然后再跳转到原定义位置。