Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save midsonlajeanty/72433c826a13eacb319bd6c20a413802 to your computer and use it in GitHub Desktop.

Select an option

Save midsonlajeanty/72433c826a13eacb319bd6c20a413802 to your computer and use it in GitHub Desktop.
Vite Plugin for Spatie Laravel Typescript Transformer (https://github.com/spatie/laravel-typescript-transformer)
import osPath from "path";
import { minimatch } from "minimatch";
import { HmrContext, Logger, Plugin } from 'vite';
import { PluginContext } from 'rollup';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
interface TypescriptTransformOptions {
patterns?: string[];
command?: string;
}
export const laravelTypescriptTransformer = ({ patterns = ['app/Data/**/*.php'], command = "php artisan typescript:transform" }: TypescriptTransformOptions = {}): Plugin => {
const runCommand = async (context: PluginContext | Logger) => {
try {
await execAsync(command);
context.info('Types generated successfully');
} catch (error: any) {
context.error(`Error: ${error.message}`);
}
};
return {
name: 'vite-plugin-laravel-typescript-transformer',
enforce: "pre",
async buildStart() {
await runCommand(this);
},
async handleHotUpdate({ file, server }) {
if (shouldRun(patterns, { file, server })) {
await runCommand(server.config.logger);
}
},
};
};
const shouldRun = (
patterns: string[],
opts: Pick<HmrContext, "file" | "server">,
): boolean => {
const file = opts.file.replaceAll("\\", "/");
return patterns.some((pattern) => {
pattern = osPath
.resolve(opts.server.config.root, pattern)
.replaceAll("\\", "/");
return minimatch(file, pattern);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment