Skip to content

Instantly share code, notes, and snippets.

@pimlie
Created October 23, 2018 15:11
Show Gist options
  • Save pimlie/a7c0642dcaff3ace66da85b4be2b6b81 to your computer and use it in GitHub Desktop.
Save pimlie/a7c0642dcaff3ace66da85b4be2b6b81 to your computer and use it in GitHub Desktop.
/**
* Merge this in your nuxt.config.js or copy to examples/hello-world
* yarn build
* yarn start
* open index in browser (dont click About)
* edit and change pages/about.vue
* yarn build && yarn start
* click About in browser
* => page reloads
*/
import { resolve } from 'path'
import fs from 'fs'
import { promisify } from 'util'
const readDir = promisify(fs.readdir)
const readFile = promisify(fs.readFile)
let previousWebpackChunks = {}
// maybe better to use save-eval package?
const saferEval = (window, code) => {
"use strict"
let l
try {
eval(code)
} catch(e) {
// ignore potential errors
}
}
export default {
hooks: {
build: {
async before(builder, buildOptions) {
const chunksPath = resolve(builder.nuxt.options.buildDir, 'dist', 'client')
if (fs.existsSync(chunksPath)) {
const chunkFiles = (await readDir(chunksPath)).filter(file => file.endsWith('.js'))
if (chunkFiles) {
await Promise.all(chunkFiles.map(async (file) => {
const window = {}
const webpackCode = await readFile(resolve(chunksPath, file), 'utf8')
// only page chunks
if (webpackCode.startsWith('(window.webpackJsonp')) {
saferEval(window, webpackCode)
const data = window.webpackJsonp.map((chunk) => {
const codeBlocks = {}
Object.keys(chunk[1]).forEach((id) => {
codeBlocks[id] = 'fnReload'
})
return [
chunk[0],
codeBlocks
]
})
previousWebpackChunks[file] = data
}
}))
}
}
},
done: (builder) => {
const chunksPath = resolve(builder.nuxt.options.buildDir, 'dist', 'client')
if (fs.existsSync(chunksPath)) {
Object.keys(previousWebpackChunks).forEach((file) => {
const filePath = resolve(chunksPath, file)
if (!fs.existsSync(filePath)) {
const jsCode = previousWebpackChunks[file].reduce((acc, value) => {
acc += '(window.webpackJsonp=window.webpackJsonp||[]).push('
acc += JSON.stringify(value).replace(/['"]fnReload['"]/g, 'function(){window.location.reload(true)}')
acc += ');'
return acc
}, '')
fs.writeFileSync(filePath, jsCode + 'window.location.reload(true);')
}
})
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment