unplugin/unplugin-vue-components

[QUESTION] Auto-import custom directives

go4cas opened this issue · 1 comments

Is there a guideline on how to auto-import custom directives (Vue 3, using Vite)?

In the config, I have set directives: true and even added dirs: ['./src/components', './src/directives'],, but somehow I still get "Failed to resolve directive: format " warnings.

Anything else I missed in the config? How should the directive be structured in the file?

@go4cas It does, but you need to write a custom resolver.

Instead of:

unpluginVueComponents({
  directives: true,
  dirs: ["./src/components", "./src/directives"],
}),

Use something like:

import { kebabCase } from "lodash-es";
import fs from "node:fs/promises";

unpluginVueComponents({
  dirs: ["./src/components"],
  resolvers: [
    {
      type: "directive",
      resolve: async (name) => {
        // Convert the filename so that it's exactly the same on disk and
        // when used.
        const filename = `v-${kebabCase(name)}.js`;

        // Check that the file exists, otherwise it would create imports
        // pointing nowhere for all directives that don't exist.
        return (await fs.exists(`src/directives/${filename}`))
          ? // The path has to be absolute (or aliased).
            `@directives/${filename}`
          : null;
      },
    },
  ],
}),

The directive files then have to each export the directive as the default export:

export default {
  mounted() {
    // …
  },
  updated() {
    // …
  },
  unmounted() {
    // …
  },
};