Skip to content

Instantly share code, notes, and snippets.

@mohammed-io
Created December 10, 2021 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohammed-io/7a689fef6a91c4e560db659b8a772652 to your computer and use it in GitHub Desktop.
Save mohammed-io/7a689fef6a91c4e560db659b8a772652 to your computer and use it in GitHub Desktop.
A patch to make the Vite HMR work with Tailwind JIT
import { utimes } from 'fs/promises'
import { debounce } from 'lodash'
import path from 'path'
import { ViteDevServer } from 'vite'
const touchFile = async path => {
const time = new Date()
return utimes(path, time, time)
}
const debouncedTouch = debounce(touchFile, 100)
export function tailwindJitPatchPlugin({
entryFile = './src/index.css',
enabled = true,
} = {}) {
return {
name: 'tailwind-jit-patch-plugin',
apply: 'serve',
configureServer({ ws, watcher, config: { logger } }: ViteDevServer) {
if (!enabled) return
logger.info(
'EXPERIMENTAL! Tailwind Jit Patch Plugin - it might be buggy, but this is the only solution at the moment'
)
const originalSend = ws.send.bind(ws)
ws.send = update => {
originalSend(update)
const anyJsUpdate = update.updates?.some(u => u.type === 'js-update')
if (!anyJsUpdate) return
const theEntryFile = update.updates?.find(
u => `.${u.path}` === entryFile
)
if (theEntryFile) return
logger.info(`touching ${entryFile}`)
debouncedTouch(path.resolve(process.cwd(), entryFile))
}
// For Tailwind 3.0
const originalAdd = watcher.add.bind(watcher)
watcher.add = file => {
if (
['true', true, 1, '1'].includes(process.env.TAILWIND_DISABLE_TOUCH) &&
file.match(/tmp-\d+-\w{12}/)
)
return
return originalAdd(file)
}
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment