Created
July 4, 2024 21:51
-
-
Save maietta/cc9385bb45a366cfe394b3f188d0230a to your computer and use it in GitHub Desktop.
Add as a postinall for package upgrades to fix "hydration mismatch" error.
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
// Patches bits-ui's Link Preview trigger component to use Runes in Svelte 5. A hydration mismatch occurs which breaks Svelte 5 apps. | |
// Running this with the postinstall task, defined in packages.json, will ensure that this file gets patched on updates until this is fixed. | |
const fs = require('fs'); | |
const path = require('path'); | |
// Define the file path | |
const filePath = path.join(__dirname, 'node_modules', 'bits-ui', 'dist', 'bits', 'link-preview', 'components', 'link-preview-trigger.svelte'); | |
// Read the file | |
fs.readFile(filePath, 'utf8', (err, data) => { | |
if (err) { | |
console.error('Error reading the file:', err); | |
return; | |
} | |
// Define the props declaration | |
const propsDeclaration = 'let { children } = $props();'; | |
// Check if let { children } = $props(); already exists | |
if (!data.includes(propsDeclaration)) { | |
// Find the </script> tag and ensure let { children } = $props(); is before it | |
const scriptTagIndex = data.lastIndexOf('</script>'); | |
if (scriptTagIndex === -1) { | |
console.error('No </script> tag found in the file.'); | |
return; | |
} | |
// Insert let { children } = $props(); before the </script> tag | |
const beforeScript = data.substring(0, scriptTagIndex); | |
const afterScript = data.substring(scriptTagIndex); | |
data = beforeScript + '\n' + propsDeclaration + '\n' + afterScript; | |
} | |
// Replace all instances of <slot {builder} /> with {@render children(builder)} considering possible whitespace | |
const finalData = data.replace(/\s*<\s*slot\s*{builder}\s*\/\s*>/g, '{@render children(builder)}'); | |
// Write the changes back to the file | |
fs.writeFile(filePath, finalData, 'utf8', (err) => { | |
if (err) { | |
console.error('Error writing the file:', err); | |
return; | |
} | |
console.log('File successfully updated.'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment