Created
April 26, 2023 18:09
-
-
Save lindesvard/c5b338ff14a8d7d9c56d07f288b0628f to your computer and use it in GitHub Desktop.
# Nextjs 13 - Clean rsc data from all html files
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 fs from 'fs' | |
import path from 'path' | |
function findRecursive(startPath: string, filter: string): string[] { | |
if (!fs.existsSync(startPath)) { | |
return [] | |
} | |
const found = [] | |
const files = fs.readdirSync(startPath) | |
for (let i = 0; i < files.length; i++) { | |
const filename = path.join(startPath, files[i]) | |
const stat = fs.lstatSync(filename) | |
if (stat.isDirectory()) { | |
found.push(...findRecursive(filename, filter)) | |
} else if (filename.endsWith(filter)) { | |
found.push(filename) | |
} | |
} | |
return found | |
} | |
const byteSize = (str: string) => round(Buffer.byteLength(str, 'utf-8') * 0.001) | |
const round = (num: number) => Math.round((num + Number.EPSILON) * 100) / 100 | |
async function main() { | |
const nextDir = path.resolve(__dirname, '..', '.next') | |
if (!fs.existsSync(nextDir)) { | |
return console.error('Missing dist folder', nextDir) | |
} | |
const files = findRecursive(nextDir, '.html') | |
for (const filepath of files) { | |
try { | |
const fileContent = fs.readFileSync(filepath, { encoding: 'utf-8' }) | |
const fixedContent = fileContent.replaceAll( | |
/<script>\(?self.__next_f(.+?)<\/script>/g, | |
'' | |
) | |
fs.writeFileSync(filepath, fixedContent, { encoding: 'utf-8' }) | |
const oldSize = byteSize(fileContent) | |
const newSize = byteSize(fixedContent) | |
console.log(`[OK] Fixed ${filepath}`) | |
console.log(` Old size: ${oldSize}kb`) | |
console.log( | |
` new size: ${newSize}kb (${round( | |
(1 - newSize / oldSize) * 100 | |
)}% smaller)` | |
) | |
} catch (e) { | |
console.error(`[Error] Failed fixing ${filepath}`) | |
console.error(e) | |
} | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment