Top Related Projects
📦 Webpack loader for Vue.js components
🛠️ webpack-based tooling for Vue.js Development
Next generation frontend tooling. It's fast!
📲 On-demand components auto importing for Vue
The Intuitive Vue Framework.
Quick Overview
Unplugin-vue-components is a Vue.js plugin that automatically imports and registers Vue components on-demand. It supports Vue 2 and Vue 3, works with various build tools, and can be used with TypeScript. This plugin simplifies component management and improves development efficiency.
Pros
- Automatic component importing and registration
- Supports Vue 2 and Vue 3
- Compatible with multiple build tools (Vite, Webpack, Rollup, esbuild)
- TypeScript support
Cons
- May increase initial build time for large projects
- Potential for naming conflicts if not configured properly
- Learning curve for proper configuration and usage
- Limited control over component registration order
Code Examples
- Basic usage with Vite:
// vite.config.js
import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
export default defineConfig({
plugins: [
Vue(),
Components(),
],
})
- Custom component resolvers:
// vite.config.js
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default {
plugins: [
Components({
resolvers: [ElementPlusResolver()],
}),
],
}
- TypeScript support:
// components.d.ts
declare module '@vue/runtime-core' {
export interface GlobalComponents {
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
}
}
export {}
Getting Started
- Install the plugin:
npm i -D unplugin-vue-components
- Add to your Vite config:
// vite.config.js
import Components from 'unplugin-vue-components/vite'
export default {
plugins: [
Components({
// options
}),
],
}
- Start using components without importing:
<template>
<div>
<MyComponent />
</div>
</template>
Competitor Comparisons
📦 Webpack loader for Vue.js components
Pros of vue-loader
- Integrated with Vue's Single-File Component (SFC) system
- Provides hot-reloading out of the box
- Supports custom blocks in Vue components
Cons of vue-loader
- Requires configuration in build tools like webpack
- Limited to Vue-specific use cases
- May have a steeper learning curve for beginners
Code Comparison
vue-loader:
module.exports = {
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
}
}
unplugin-vue-components:
import Components from 'unplugin-vue-components/vite'
export default {
plugins: [
Components({
// options
})
]
}
Key Differences
- vue-loader is specifically designed for Vue SFCs, while unplugin-vue-components focuses on auto-importing components
- unplugin-vue-components works across multiple build tools (Vite, webpack, Rollup) without additional configuration
- vue-loader requires manual registration of components, whereas unplugin-vue-components automates this process
Use Cases
- Choose vue-loader for traditional Vue projects with webpack and full SFC support
- Opt for unplugin-vue-components when you want automatic component imports and flexibility across build tools
🛠️ webpack-based tooling for Vue.js Development
Pros of vue-cli
- Comprehensive project scaffolding and build setup
- Integrated development environment with hot-reloading
- Official Vue.js tool with extensive documentation and community support
Cons of vue-cli
- Heavier setup and configuration compared to unplugin-vue-components
- Less flexible for custom build processes or non-standard project structures
- May include unnecessary features for simpler projects
Code Comparison
vue-cli (vue.config.js):
module.exports = {
configureWebpack: {
plugins: [
new VueLoaderPlugin(),
// Other plugins...
]
}
}
unplugin-vue-components (vite.config.js):
import Components from 'unplugin-vue-components/vite'
export default {
plugins: [
Components({ /* options */ }),
],
}
The vue-cli configuration is more extensive and requires manual setup of plugins, while unplugin-vue-components offers a more streamlined approach for component auto-importing. unplugin-vue-components is designed to work with various build tools, including Vite, webpack, and Rollup, providing greater flexibility. However, vue-cli offers a more comprehensive development environment and project structure, which can be beneficial for larger, more complex applications.
Next generation frontend tooling. It's fast!
Pros of Vite
- Broader scope: Vite is a full-featured build tool and development server for modern web projects
- Faster development experience with native ES modules and instant hot module replacement (HMR)
- Supports multiple frameworks beyond Vue, including React, Svelte, and vanilla JavaScript
Cons of Vite
- Steeper learning curve due to its comprehensive feature set
- May be overkill for smaller projects or those focused solely on Vue components
- Requires more configuration for advanced use cases
Code Comparison
Vite configuration:
// vite.config.js
export default {
plugins: [vue()],
build: { /* build options */ },
server: { /* server options */ }
}
unplugin-vue-components usage:
// vite.config.js
import Components from 'unplugin-vue-components/vite'
export default {
plugins: [Components({ /* options */ })]
}
Key Differences
- Vite is a complete build tool, while unplugin-vue-components is a specific plugin for auto-importing Vue components
- unplugin-vue-components focuses on simplifying component imports in Vue projects
- Vite provides a more comprehensive development environment with features like pre-bundling and optimized builds
Use Cases
- Choose Vite for full-stack web projects requiring a robust build tool and development server
- Opt for unplugin-vue-components when working on Vue-specific projects and prioritizing simplified component management
📲 On-demand components auto importing for Vue
Pros of unplugin-vue-components
- Automatic component importing for Vue 3 and Vue 2
- Supports multiple component libraries and custom resolvers
- Compatible with various build tools (Vite, Webpack, Rollup, esbuild)
Cons of unplugin-vue-components
- May require additional configuration for complex setups
- Potential performance impact on large projects with many components
Code Comparison
Both repositories are the same, so there's no code comparison to make. Here's a sample usage of unplugin-vue-components:
// vite.config.js
import Components from 'unplugin-vue-components/vite'
export default defineConfig({
plugins: [
Components({
// options
}),
],
})
Summary
unplugin-vue-components is a versatile plugin for automatically importing Vue components. It offers support for multiple Vue versions and build tools, making it a valuable asset for streamlining development workflows. However, users should be aware of potential configuration complexities and performance considerations in larger projects. The plugin's flexibility and ease of use make it a popular choice among Vue developers seeking to optimize their component management.
The Intuitive Vue Framework.
Pros of Nuxt
- Full-featured framework for building Vue.js applications with server-side rendering, static site generation, and more
- Integrated development environment with automatic code splitting, hot module replacement, and optimized production builds
- Rich ecosystem with official and community modules for various functionalities
Cons of Nuxt
- Steeper learning curve due to its comprehensive nature and additional concepts
- Potentially heavier initial setup and configuration compared to simpler plugins
- May introduce unnecessary complexity for smaller projects or single-page applications
Code Comparison
Nuxt (pages/index.vue):
<template>
<div>
<h1>{{ title }}</h1>
<NuxtLink to="/about">About</NuxtLink>
</div>
</template>
<script>
export default {
data: () => ({ title: 'Welcome to Nuxt' })
}
</script>
unplugin-vue-components (main.js):
import { createApp } from 'vue'
import App from './App.vue'
import Components from 'unplugin-vue-components/vite'
createApp(App).mount('#app')
// Vite plugin configuration
Components({
dirs: ['src/components']
})
The code comparison showcases Nuxt's built-in routing and page structure, while unplugin-vue-components focuses on automatic component imports in a standard Vue.js application.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
unplugin-vue-components
On-demand components auto importing for Vue.
Features
- ð Supports both Vue 2 and Vue 3 out-of-the-box.
- ⨠Supports both components and directives.
- â¡ï¸ Supports Vite, Webpack, Rspack, Vue CLI, Rollup, esbuild and more, powered by unplugin.
- ð Tree-shakable, only registers the components you use.
- ðª Folder names as namespaces.
- 𦾠Full TypeScript support.
- ð Built-in resolvers for popular UI libraries.
- ð Works perfectly with unplugin-icons.
Installation
npm i unplugin-vue-components -D
vite-plugin-components
has been renamed tounplugin-vue-components
, see the migration guide.
Vite
// vite.config.ts
import Components from 'unplugin-vue-components/vite'
export default defineConfig({
plugins: [
Components({ /* options */ }),
],
})
Rollup
// rollup.config.js
import Components from 'unplugin-vue-components/rollup'
export default {
plugins: [
Components({ /* options */ }),
],
}
Webpack
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-components/webpack')({ /* options */ }),
],
}
Rspack
// rspack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-components/rspack')({ /* options */ }),
],
}
Vue CLI
// vue.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-components/webpack')({ /* options */ }),
],
}
You can also rename the Vue configuration file to vue.config.mjs
and use static import syntax (you should use latest @vue/cli-service ^5.0.8
):
// vue.config.mjs
import Components from 'unplugin-vue-components/webpack'
export default {
configureWebpack: {
plugins: [
Components({ /* options */ }),
],
},
}
esbuild
// esbuild.config.js
import { build } from 'esbuild'
import Components from 'unplugin-vue-components/esbuild'
build({
/* ... */
plugins: [
Components({
/* options */
}),
],
})
Usage
Use components in templates as you would usually do, it will import components on demand, and there is no import
and component registration
required anymore! If you register the parent component asynchronously (or lazy route), the auto-imported components will be code-split along with their parent.
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>
Note By default this plugin will import components in the
src/components
path. You can customize it using thedirs
option.
TypeScript
To get 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.
Components({
dts: true, // enabled by default if `typescript` is installed
})
Once the setup is done, a components.d.ts
will be generated and updates automatically with the type definitions. Feel free to commit it into git or not as you want.
Make sure you also add
components.d.ts
to yourtsconfig.json
underinclude
.
Importing from UI Libraries
We have several built-in resolvers for popular UI libraries like Vuetify, Ant Design Vue, and Element Plus, where you can enable them by:
Supported Resolvers:
- Ant Design Vue
- Arco Design Vue
- BootstrapVue
- Element Plus
- Element UI
- Headless UI
- IDux
- Inkline
- Ionic
- Naive UI
- Prime Vue
- Quasar
- TDesign
- Vant
@vant/auto-import-resolver
- Vant's own auto-import resolver
- Varlet UI
@varlet/import-resolver
- Varlet's own auto-import resolver
- VEUI
- View UI
- Vuetify — Prefer first-party plugins when possible: v3 + vite, v3 + webpack, v2 + webpack
- VueUse Components
- VueUse Directives
- Dev UI
import {
AntDesignVueResolver,
ElementPlusResolver,
VantResolver,
} from 'unplugin-vue-components/resolvers'
// vite.config.js
import Components from 'unplugin-vue-components/vite'
// your plugin installation
Components({
resolvers: [
AntDesignVueResolver(),
ElementPlusResolver(),
VantResolver(),
],
})
You can also write your own resolver quickly:
Components({
resolvers: [
// example of importing Vant
(componentName) => {
// where `componentName` is always CapitalCase
if (componentName.startsWith('Van'))
return { name: componentName.slice(3), from: 'vant' }
},
],
})
Types for global registered components
Some libraries might register some global components for you to use anywhere (e.g. Vue Router provides <RouterLink>
and <RouterView>
). Since they are global available, there is no need for this plugin to import them. However, those are commonly not TypeScript friendly, and you might need to register their types manually.
Thus unplugin-vue-components
provided a way to only register types for global components.
Components({
dts: true,
types: [{
from: 'vue-router',
names: ['RouterLink', 'RouterView'],
}],
})
So the RouterLink
and RouterView
will be presented in components.d.ts
.
By default, unplugin-vue-components
detects supported libraries automatically (e.g. vue-router
) when they are installed in the workspace. If you want to disable it completely, you can pass an empty array to it:
Components({
// Disable type only registration
types: [],
})
Migrate from vite-plugin-components
package.json
{
"devDependencies": {
- "vite-plugin-components": "*",
+ "unplugin-vue-components": "^0.14.0",
}
}
vite.config.js
- import Components, { ElementPlusResolver } from 'vite-plugin-components'
+ import Components from 'unplugin-vue-components/vite'
+ import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default {
plugins: [
/* ... */
Components({
/* ... */
// `customComponentsResolvers` has renamed to `resolver`
- customComponentsResolvers: [
+ resolvers: [
ElementPlusResolver(),
],
// `globalComponentsDeclaration` has renamed to `dts`
- globalComponentsDeclaration: true,
+ dts: true,
// `customLoaderMatcher` is depreacted, use `include` instead
- customLoaderMatcher: id => id.endsWith('.md'),
+ include: [/\.vue$/, /\.vue\?vue/, /\.vue\.[tj]sx?\?vue/, /\.md$/],
}),
],
}
Configuration
The following show the default values of the configuration
Components({
// relative paths to the directory to search for components.
dirs: ['src/components'],
// valid file extensions for components.
extensions: ['vue'],
// Glob patterns to match file names to be detected as components.
// You can also specify multiple like this: `src/components/*.{vue,tsx}`
// When specified, the `dirs`, `extensions`, and `directoryAsNamespace` options will be ignored.
// If you want to exclude components being registered, use negative globs with leading `!`.
globs: ['src/components/*.vue'],
// search for subdirectories
deep: true,
// resolvers for custom components
resolvers: [],
// generate `components.d.ts` global declarations,
// also accepts a path for custom filename
// default: `true` if package typescript is installed
dts: false,
// Allow subdirectories as namespace prefix for components.
directoryAsNamespace: false,
// Collapse same prefixes (camel-sensitive) of folders and components
// to prevent duplication inside namespaced component name.
// works when `directoryAsNamespace: true`
collapseSamePrefixes: false,
// Subdirectory paths for ignoring namespace prefixes.
// works when `directoryAsNamespace: true`
globalNamespaces: [],
// auto import for directives
// default: `true` for Vue 3, `false` for Vue 2
// Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
// To install Babel, run: `npm install -D @babel/parser`
directives: true,
// Transform path before resolving
importPathTransform: v => v,
// Allow for components to override other components with the same name
allowOverrides: false,
// Filters for transforming targets (components to insert the auto import)
// Note these are NOT about including/excluding components registered - use `globs` or `excludeNames` for that
include: [/\.vue$/, /\.vue\?vue/, /\.vue\.[tj]sx?\?vue/],
exclude: [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/],
// Filters for component names that will not be imported
// Use for globally imported async components or other conflicts that the plugin cannot detect
excludeNames: [/^Async.+/],
// Vue version of project. It will detect automatically if not specified.
// Acceptable value: 2 | 2.7 | 3
version: 2.7,
// Only provide types of components in library (registered globally)
types: []
})
Example
Vitesse starter template.
Thanks
Thanks to @brattonross, this project is heavily inspired by vite-plugin-voie.
License
MIT License © 2020-PRESENT Anthony Fu
Top Related Projects
📦 Webpack loader for Vue.js components
🛠️ webpack-based tooling for Vue.js Development
Next generation frontend tooling. It's fast!
📲 On-demand components auto importing for Vue
The Intuitive Vue Framework.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot