Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

📲 On-demand components auto importing for Vue

License

NotificationsYou must be signed in to change notification settings

unplugin/unplugin-vue-components

Repository files navigation

NPM version

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 byunplugin.
  • 🏝 Tree-shakable, only registers the components you use.
  • 🪐 Folder names as namespaces.
  • 🦾 Full TypeScript support.
  • 🌈Built-in resolvers for popular UI libraries.
  • 😃 Works perfectly withunplugin-icons.


Installation

npm i unplugin-vue-components -D

vite-plugin-components has been renamed tounplugin-vue-components, see themigration guide.

Vite
// vite.config.tsimportComponentsfrom'unplugin-vue-components/vite'exportdefaultdefineConfig({plugins:[Components({/* options */}),],})


Rollup
// rollup.config.jsimportComponentsfrom'unplugin-vue-components/rollup'exportdefault{plugins:[Components({/* options */}),],}


Webpack
// webpack.config.jsmodule.exports={/* ... */plugins:[require('unplugin-vue-components/webpack')({/* options */}),],}


Rspack
// rspack.config.jsmodule.exports={/* ... */plugins:[require('unplugin-vue-components/rspack')({/* options */}),],}


Nuxt

You might not need this plugin for Nuxt. Use@nuxt/components instead.


Vue CLI
// vue.config.jsmodule.exports={/* ... */plugins:[require('unplugin-vue-components/webpack')({/* options */}),],}

You can also rename the Vue configuration file tovue.config.mjs and use static import syntax (you should use latest@vue/cli-service ^5.0.8):

// vue.config.mjsimportComponentsfrom'unplugin-vue-components/webpack'exportdefault{configureWebpack:{plugins:[Components({/* options */}),],},}


esbuild
// esbuild.config.jsimport{build}from'esbuild'importComponentsfrom'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 noimport andcomponent 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><HelloWorldmsg="Hello Vue 3.0 + Vite"/></div></template><script>exportdefault{name:'App',}</script>

into this

<template><div><HelloWorldmsg="Hello Vue 3.0 + Vite"/></div></template><script>importHelloWorldfrom'./src/components/HelloWorld.vue'exportdefault{name:'App',components:{      HelloWorld,},}</script>

NoteBy default this plugin will import components in thesrc/components path. You can customize it using thedirs option.

TypeScript

To get TypeScript support for auto-imported components, there isa 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, acomponents.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 addcomponents.d.ts to yourtsconfig.json underinclude.

Importing from UI Libraries

We have several built-in resolvers for popular UI libraries likeVuetify,Ant Design Vue, andElement Plus, where you can enable them by:

Supported Resolvers:

import{AntDesignVueResolver,ElementPlusResolver,VantResolver,}from'unplugin-vue-components/resolvers'// vite.config.jsimportComponentsfrom'unplugin-vue-components/vite'// your plugin installationComponents({resolvers:[AntDesignVueResolver(),ElementPlusResolver(),VantResolver(),],})

You can also write your own resolver quickly:

Components({resolvers:[// example of importing Vant(componentName)=>{// where `componentName` is always CapitalCaseif(componentName.startsWith('Van'))return{name:componentName.slice(3),from:'vant'}},],})

We no longer accept new resolvers.

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.

Thusunplugin-vue-components provided a way to only register types for global components.

Components({dts:true,types:[{from:'vue-router',names:['RouterLink','RouterView'],}],})

So theRouterLink andRouterView will be presented incomponents.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 registrationtypes:[],})

Migrate fromvite-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 subdirectoriesdeep:true,// resolvers for custom componentsresolvers:[],// generate `components.d.ts` global declarations,// also accepts a path for custom filename// default: `true` if package typescript is installeddts: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 resolvingimportPathTransform:v=>v,// Allow for components to override other components with the same nameallowOverrides: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 thatinclude:[/\.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 detectexcludeNames:[/^Async.+/],// Vue version of project. It will detect automatically if not specified.// Acceptable value: 2 | 2.7 | 3version:2.7,// Only provide types of components in library (registered globally)// see https://github.com/unplugin/unplugin-vue-components/blob/main/src/core/type-imports/index.tstypes:[/* ... */],})

Example

Vitesse starter template.

Thanks

Thanks to@brattonross, this project is heavily inspired byvite-plugin-voie.

License

MIT License © 2020-PRESENTAnthony Fu


[8]ページ先頭

©2009-2025 Movatter.jp