Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Layouts names typings? #156

Open
sachyshyn opened this issue Aug 6, 2024 · 0 comments
Open

Layouts names typings? #156

sachyshyn opened this issue Aug 6, 2024 · 0 comments

Comments

@sachyshyn
Copy link

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?

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant