Plugins

Intermediate · 8 min

Packaging app-wide setup behind app.use, what an install function can register, the createX factory pattern, and pairing a plugin with a composable.

Before thisProvide and injectCustom directives

LearnVue · 8 min

Plugins

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by LearnVueReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A Vue plugin is an object with an install(app, options) method, or a plain function with the same signature, and app.use(plugin, options) calls it once with the app instance.
  • Inside install, a plugin can do anything the app instance allows: register global components and directives, provide values to every component, add global properties, or set app-level config like an error handler.
  • Libraries such as Vue Router and Pinia are plugins, and the createRouter() and createPinia() calls you pass to app.use are factories that build a configured plugin object.
  • The modern way to hand a plugin's services to components is app.provide paired with a composable that calls inject, rather than adding $-prefixed properties to app.config.globalProperties.
  • With TypeScript, a typed InjectionKey gives provide and inject a shared type, and global properties need a module augmentation of ComponentCustomProperties to be type-checked in templates.

The problem: setup that every app repeats

Look at the main.js of a growing Vue app and you’ll find a list of global registrations: a few base components, a directive or two, an error handler, some values provided to the whole tree.

const app = createApp(App)
app.component('BaseButton', BaseButton)
app.component('BaseInput', BaseInput)
app.directive('focus', vFocus)
app.provide('apiBaseUrl', import.meta.env.VITE_API_URL)
app.config.errorHandler = reportToSentry
app.mount('#app')

That’s fine for one app. When a second app (an admin panel, a design-system playground, a test harness) needs the same setup, you have two options: copy the block or package it. A plugin is the package.

A plugin is an install function

A plugin is either an object with an install method or a plain function. Vue calls it with the app instance and whatever options you passed to app.use:

// plugins/ui.js
import BaseButton from '../components/BaseButton.vue'
import BaseInput from '../components/BaseInput.vue'
import { vFocus } from '../directives/focus'

export default {
  install(app, options = {}) {
    const prefix = options.prefix ?? 'Base'
    app.component(`${prefix}Button`, BaseButton)
    app.component(`${prefix}Input`, BaseInput)
    app.directive('focus', vFocus)
  },
}
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import ui from './plugins/ui'

createApp(App).use(ui, { prefix: 'Ui' }).mount('#app')

That’s all app.use does: call install(app, options). There’s no plugin registry and no lifecycle. app.use returns the app, so calls chain, and it should run before mount. Vue also remembers which plugins it has installed on an app, so passing the same plugin twice installs it once and logs a warning.

What install can do

Anything the app instance can do, a plugin can do:

Inside install What it gives every component
app.component(name, comp) A component usable in any template without importing it
app.directive(name, dir) A custom directive usable as v-name anywhere
app.provide(key, value) A value any component can inject (see provide and inject)
app.config.globalProperties.$x = ... A property on every component instance, reachable as this.$x or $x in templates
app.config.errorHandler = fn One handler for uncaught errors from components (see error handling)

The last two rows are older tools. globalProperties exists mostly for Options API code, where this is how you reach things. In <script setup> there’s no this, so a service hung on globalProperties is awkward to reach. That leads to the pattern current libraries use.

The modern shape: provide plus a composable

Instead of a global property, the plugin provides a service under a key, and a small composable injects it. Here’s a toast-notification plugin built that way:

// plugins/toast.ts
import { reactive, inject, type App, type InjectionKey } from 'vue'
import ToastContainer from '../components/ToastContainer.vue'

interface Toast { id: number; text: string }
interface ToastService {
  toasts: Toast[]
  show(text: string, ms?: number): void
}

const ToastKey: InjectionKey<ToastService> = Symbol('toast')

export function createToast(defaults: { duration?: number } = {}) {
  let nextId = 0
  const service = reactive<ToastService>({
    toasts: [],
    show(text, ms = defaults.duration ?? 3000) {
      const id = nextId++
      service.toasts.push({ id, text })
      setTimeout(() => {
        service.toasts = service.toasts.filter((t) => t.id !== id)
      }, ms)
    },
  })

  return {
    install(app: App) {
      app.provide(ToastKey, service)
      app.component('ToastContainer', ToastContainer)
    },
  }
}

export function useToast(): ToastService {
  const service = inject(ToastKey)
  if (!service) throw new Error('useToast() called without the toast plugin installed')
  return service
}
// main.ts
createApp(App).use(createToast({ duration: 4000 })).mount('#app')
<!-- Any component, anywhere in the tree -->
<script setup lang="ts">
import { useToast } from '@/plugins/toast'
const toast = useToast()
</script>

<template>
  <button @click="toast.show('Saved')">Save</button>
</template>

Three things in this design are worth copying.

The factory. createToast(options) builds the service and returns the plugin. Each call makes a fresh instance, so two apps on one page, or two server-rendered requests, never share toast state. Module-level state would leak between them.

The typed key. InjectionKey<ToastService> is a symbol that carries a type, so inject(ToastKey) comes back typed without a cast.

The composable as the public API. Components call useToast(), not inject(ToastKey). The key stays private to the module, the missing-plugin case gets a clear error, and a component’s dependency on the service shows up in its imports.

You already use plugins every day

This is exactly how the official libraries are built:

import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { createPinia } from 'pinia'

const router = createRouter({ history: createWebHistory(), routes })

createApp(App)
  .use(createPinia())
  .use(router)
  .mount('#app')

createRouter and createPinia are factories returning plugin objects. When Vue Router’s plugin installs, it registers RouterLink and RouterView globally, provides the router and the current route, and adds $router and $route global properties for Options API code. useRouter() and useRoute() are the composables that inject those provided values: the same shape as useToast. The Vue Router and Pinia lessons cover them in detail.

Typing global properties

If a plugin does add a global property (often for Options API compatibility), augment Vue’s types so templates and this know about it:

declare module 'vue' {
  interface ComponentCustomProperties {
    $toast: ToastService
  }
}

That’s TypeScript module augmentation. Without it, $toast compiles in templates as an unknown property.

Calling inject outside a component

inject normally only works during a component’s setup. Code like a router navigation guard runs outside any component, but sometimes needs a provided value. Since Vue 3.3, app.runWithContext(fn) runs a function with the app as the injection context, so inject inside it resolves against app.provide. Libraries use this internally; in app code you’ll rarely need it, but it explains how a store can be used inside a guard.

What the video covers

LearnVue’s video builds a Vue 3 plugin from scratch: the object with install(app, options), passing options through app.use, and attaching app-wide functionality from inside install. It’s a clear, focused walkthrough from 2021. The provide-plus-composable pattern current libraries favor, the createX factory reasoning, TypeScript typing, and runWithContext all postdate it or fall outside it, so the lesson carries those.

Where this fits

Plugins, composables, and directives all reuse things you’d otherwise write in templates and setup code. The last lesson in this group goes underneath templates entirely: render functions and JSX.

Check yourself

  1. 01What is the difference between writing app.component('BaseButton', BaseButton) in main.js and doing the same inside a plugin's install function?

    At runtime, none: install receives the same app instance and calls the same method. The difference is packaging. A plugin bundles several of these registrations, plus any configuration they need, behind one app.use call that can be shared across apps or published as a library.

  2. 02Your plugin needs to give components access to a notifications service. Why is app.provide plus a useNotifications() composable usually better than app.config.globalProperties.$notify?

    globalProperties are only reachable through this or directly in templates, so they don't work naturally inside <script setup> or other composables, and they need a ComponentCustomProperties augmentation to be typed. A provided value reached through a composable that calls inject works anywhere in setup, can use a typed InjectionKey, and makes each component's dependency on the service visible in its imports.

  3. 03Why do libraries expose createRouter(options) or createPinia() instead of a plugin object you pass straight to app.use?

    The factory lets each app get its own configured instance. Options like the route table are passed to the factory, and the returned object carries both the install method and the instance's API. That keeps state from leaking between apps, which matters when several apps share a page, and on the server, where each request needs a fresh instance.

  4. 04What happens if the same plugin is passed to app.use twice?

    Vue remembers which plugins an app has installed and skips the second install, logging a development warning that the plugin has already been applied. The plugin's install function runs only once per app.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark