On demand components auto importing for Vite
Install
npm i vite-plugin-components -D # yarn add vite-plugin-components -D
Add it to vite.config.js
// vite.config.js
import ViteComponents from 'vite-plugin-components'
export default {
plugins: [
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>
The following show the default values of the configuration
ViteComponents({
// relative paths to the directory to search for components.
dirs: ['src/components'],
// valid file extensions for components.
extensions: ['vue'],
// search for subdirectories
deep: true,
// Allow subdirectories as namespace prefix for components.
directoryAsNamespace: false,
// Subdirectory paths for ignoring namespace prefixes
// works when `directoryAsNamespace: true`
globalNamespaces: [],
// vite config
// currently, vite does not provide an API for plugins to get the config https://github.com/vitejs/vite/issues/738
// you will need to pass `alias` and `root` if you set them in vite config
alias: {},
root: process.cwd(),
})
See the Vitesse starter template.
Thanks to @brattonross, this project is heavily inspired by vite-plugin-voie.
MIT License © 2020 Anthony Fu