vite-plugin-vue-layouts icon indicating copy to clipboard operation
vite-plugin-vue-layouts copied to clipboard

Layouts names typings?

Open sachyshyn opened this issue 6 months ago • 0 comments

Lets imagine a case when in /layouts folder I have two layouts: default and custom. I want their names to be constant and use them to define a page layout. There is a plugin sample which helps to achieve that, but I'm not sure that writing own plugins is the best practice for creating applications.

import { type Plugin } from 'vite';
import { promises as fs } from 'fs';
import path from 'path';

function generateLayoutsDTS(layoutDir: string, dtsPath: string) {
  return async function updateLayouts() {
    const files = await fs.readdir(layoutDir);
    const layoutNames = files
      .filter(file => file.endsWith('.vue'))
      .map(file => path.basename(file, '.vue'));

    const content = `
      export const layoutNames = ${JSON.stringify(layoutNames)} as const;
      export type LayoutName = typeof layoutNames[number];
    `;

    await fs.writeFile(dtsPath, content);
  };
}

export default function generateLayoutsPlugin(layoutDir = 'src/layouts', dtsPath = 'src/layouts.d.ts'): Plugin {
  const updateLayouts = generateLayoutsDTS(layoutDir, dtsPath);

  return {
    name: 'vite-plugin-generate-layouts',
    async buildStart() {
      await updateLayouts();
    },
    async handleHotUpdate({ file, server }) {
      if (file.startsWith(layoutDir)) {
        await updateLayouts();
        server.ws.send({ type: 'full-reload' });
      }
    },
  };
}

Any thoughts?

sachyshyn avatar Aug 06 '24 11:08 sachyshyn