Skip to content

Instantly share code, notes, and snippets.

@lepikhinb
Last active December 26, 2022 21:27
Show Gist options
  • Save lepikhinb/ded05516596acad0712569bc4c5fc9f7 to your computer and use it in GitHub Desktop.
Save lepikhinb/ded05516596acad0712569bc4c5fc9f7 to your computer and use it in GitHub Desktop.
Vite plugin to run custom commands on file changes
// the plugin requires a `minimatch` dependency installed
// npm i -D minimatch
import { PluginOption } from "vite"
import { exec } from "child_process"
import minimatch from "minimatch"
import path from "path"
import chalk from "chalk"
export default function watch(config: {
pattern: string | string[]
command: string
init?: boolean
verbose?: boolean
timeout?: number
}): PluginOption {
var timeout = config.timeout ?? 500
var throttled = false
const execute = () => {
exec(config.command, (exception, output, error) => {
if (config.verbose && output) console.log(output)
if (config.verbose && error) console.error(error)
})
}
return {
name: "vite-watcher-runner",
buildStart() {
if (config.init) {
execute()
}
},
handleHotUpdate({ file, server }) {
if (throttled) return
throttled = true
setTimeout(() => (throttled = false), timeout)
let patterns = Array.of(config.pattern).flat()
let shouldRun = patterns.find(
(pattern) => minimatch(
file,
path.resolve(server.config.root, pattern)
)
)
if (shouldRun) {
console.log("Running", chalk.bold(config.command), "\n")
execute()
}
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment