覺得每次都要 import 很麻煩嗎?試試看 unplugin-vue-components 吧!
今天在練習開新專案時,覺得每次要 import 元件很麻煩,所以搜尋了一下,發現有個酷酷的套件,推薦給大家使用。
- 支援 vue 2 及 vue 3。
- 支援 Vite, Webpack, Rspack, Vue CLI, Rollup, esbuild …等主流打包工具。
- 支援 TypeScript。
這邊以 Vite 當例子示範:
- 安裝套件:
$npm install unplugin-vue-components
2. 在 vite.config.ts
中設定:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
export default defineConfig({
plugins: [
vue(),
Components({
dirs: ['src/components'], // 指定自動引入的目錄
extensions: ['vue'], // 指定元件的擴展名,可以忽略
deep: true, // 遞迴搜索子目錄
dts: 'src/components.d.ts' // 生成 TypeScript 定義文件
})
],
worker: {
format: 'es'
},
define: {
'process.env': {}
},
resolve: {
alias: [
// 其他 alias 設定
]
}
})
3. 在Vue 元件中,可以直接使用元件,而無需手動引入。例如:
<template>
<MyComponent />
</template>
<script setup>
// 無需手動引入 MyComponent
</script>
unplugin-vue-components
會自動掃描 src/components
目錄中的所有 Vue 組件,並在使用時自動引入它們。這可以大大簡化程式並提高開發效率,再也不用 import 了。
注意:
使用 unplugin-vue-components
時,元件名稱需要以大寫開頭。這是因為 Vue.js 遵循 PascalCase 命名規範,並且在模板中使用時,PascalCase 組件名稱會自動轉換為 kebab-case。
使用時:
<template>
<MyComponent />
</template>
或者:
<template>
<my-component />
</template>