Created
December 10, 2021 14:35
-
-
Save mohammed-io/7a689fef6a91c4e560db659b8a772652 to your computer and use it in GitHub Desktop.
A patch to make the Vite HMR work with Tailwind JIT
This file contains 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 { 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