Created
August 3, 2018 05:46
-
-
Save binki/e6558065360e47238240857d6cee611f to your computer and use it in GitHub Desktop.
Work Around main.«hash».js missing from service-worker.js
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
#!/usr/bin/env node | |
// Works around issue described at | |
// https://github.com/facebook/create-react-app/issues/3574#issuecomment-410141752 | |
// To use, add this as “&& ./build-precache-fixup.js” to | |
// package.json/scripts.build. | |
const crypto = require('crypto'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const assetManifest = require('./build/asset-manifest.json'); | |
const mainUri = assetManifest['main.js']; | |
const serviceWorkerJsPath = path.join('build', 'service-worker.js'); | |
const serviceWorkerJs = fs.readFileSync(serviceWorkerJsPath, 'utf-8'); | |
const matches = /(precacheConfig=)(\[\[.*?\]\])/.exec(serviceWorkerJs); | |
if (!matches || !matches[2]) { | |
throw new Error(`Unable to locate precacheConfig= in ${serviceWorkerJsPath}`); | |
} | |
const dataStringPrefix = matches[1]; | |
const dataString = matches[2]; | |
// Check if main is there. If it is, skip. | |
const data = JSON.parse(dataString); | |
const hasMain = !!data.filter(entry => { | |
return entry[0] === mainUri; | |
}).length; | |
if (!hasMain) { | |
const mainJsMd5Hash = (() => { | |
const hash = crypto.createHash('md5'); | |
hash.update(fs.readFileSync(path.join('build', mainUri))); | |
return hash.digest('hex'); | |
})(); | |
data.push([mainUri, mainJsMd5Hash]); | |
} | |
const newDataString = JSON.stringify(data); | |
// Splice into service-worker.js | |
const newServiceWorkerJs = serviceWorkerJs.substring(0, matches.index) | |
+ dataStringPrefix | |
+ newDataString | |
+ serviceWorkerJs.substring(matches.index + matches[0].length); | |
const serviceWorkerJsTmpPath = serviceWorkerJsPath + '#'; | |
fs.writeFileSync(serviceWorkerJsTmpPath, newServiceWorkerJs); | |
fs.renameSync(serviceWorkerJsTmpPath, serviceWorkerJsPath); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment