|
| 1 | +const fs = require('fs'); |
| 2 | +const hashFiles = require('hash-files'); |
| 3 | +const path = require('node:path'); |
| 4 | +const replace = require('replace-in-file'); |
| 5 | + |
| 6 | +// to facilitate cache busting: |
| 7 | +// - rename built js and css files with a short hash |
| 8 | +// - find-and-replace the names in all html |
| 9 | + |
| 10 | +// files we want to rename |
| 11 | +const filesToHash = [ |
| 12 | + 'build/css/style.min.css', |
| 13 | + 'build/js/bundle.js', |
| 14 | +]; |
| 15 | + |
| 16 | +// html files that may need string replacements |
| 17 | +const filesToPatch = 'build/**/*.html'; |
| 18 | + |
| 19 | +// replacements to make |
| 20 | +const replacements = {}; |
| 21 | + |
| 22 | +filesToHash.forEach(async (file) => { |
| 23 | + const hash = hashFiles.sync({ files: [file] }); |
| 24 | + const fileName = path.parse(file).base; |
| 25 | + const shortHash = hash.substring(0, 6); |
| 26 | + |
| 27 | + // e.g. /path/example.css becomes /path/example.789abc.css |
| 28 | + const newFile = file.replace(/^(.*)\.(.*)$/, `$1.${shortHash}.$2`); |
| 29 | + const newFileName = path.parse(newFile).base; |
| 30 | + |
| 31 | + // copy rather than rename in place |
| 32 | + fs.copyFile(file, newFile, (error) => { |
| 33 | + if (error) { |
| 34 | + console.error(error); |
| 35 | + } |
| 36 | + }); |
| 37 | + |
| 38 | + // track string replacement |
| 39 | + replacements[fileName] = newFileName; |
| 40 | +}); |
| 41 | + |
| 42 | +// find and replace the filenames throughout all passed html files |
| 43 | +// this doesn't take context into account, so beware unintended changes |
| 44 | +(async function () { |
| 45 | + try { |
| 46 | + const results = await replace({ |
| 47 | + files: filesToPatch, |
| 48 | + from: Object.keys(replacements), |
| 49 | + to: Object.values(replacements), |
| 50 | + }); |
| 51 | + console.log('cache buster replacing:', replacements); |
| 52 | + changedResults = results.filter((result) => result.hasChanged); |
| 53 | + console.log(`cache buster renamed ${changedResults.length} files`); |
| 54 | + } catch (error) { |
| 55 | + console.error('cache buster error replacing files:', error); |
| 56 | + } |
| 57 | +})(); |
0 commit comments