Created
January 25, 2026 17:00
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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