vite-plugin-components
On demand components auto importing for Vite
Usage
ℹ️ Vite 2 is supported from v0.6.x
, Vite 1's support is discontinued.
Install
npm i vite-plugin-components -D
Add it to vite.config.js
import Vue from '@vitejs/plugin-vue'
import ViteComponents from 'vite-plugin-components'
export default {
plugins: [
Vue(),
ViteComponents()
],
};
That's all.
Use components in templates as you would usually do but NO import
and component registration
required anymore! It will import components on demand, code splitting is also possible.
Basically, it will automatically turn this
<template>
<div>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
into this
<template>
<div>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</div>
</template>
<script>
import HelloWorld from './src/components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
TypeScript
To have TypeScript support for auto-imported components, there is a PR to Vue 3 extending the interface of global components. Currently, Volar has supported this usage already, if you are using Volar, you can change the config as following to get the support.
import ViteComponents from 'vite-plugin-components'
export default {
plugins: [
ViteComponents({
globalComponentsDeclaration: true,
}),
],
}
Vue 2 Support
It just works.
import { createVuePlugin } from 'vite-plugin-vue2'
import ViteComponents from 'vite-plugin-components'
export default {
plugins: [
createVuePlugin(),
ViteComponents(),
],
}
Importing from UI Libraries
We have several built-in resolver for popular UI libraries like Ant Design Vue and Element Plus, where you can enable them by:
import ViteComponents, {
AntDesignVueResolver,
ElementPlusResolver,
VantResolver,
} from 'vite-plugin-components'
export default {
plugins: [
ViteComponents({
customComponentResolvers: [
AntDesignVueResolver(),
ElementPlusResolver(),
VantResolver(),
]
}),
],
}
Or you can write your own resolver quite easily:
import ViteComponents from 'vite-plugin-components'
export default {
plugins: [
ViteComponents({
customComponentResolvers: [
(name) => {
if (name.startsWith('Van'))
return { importName: name.slice(3), path: 'vant' }
}
]
}),
],
}
If made other UI libraries configured, please feel free to contribute so it can help others using them out-of-box. Thanks!
Configuration
The following show the default values of the configuration
ViteComponents({
dirs: ['src/components'],
extensions: ['vue'],
deep: true,
directoryAsNamespace: false,
globalNamespaces: [],
})
Example
See the Vitesse starter template.
Thanks
Thanks to @brattonross, this project is heavily inspired by vite-plugin-voie.
License
MIT License © 2020 Anthony Fu