2017-04-03 18:10:24 +00:00
|
|
|
export default class PagesPlugin {
|
|
|
|
apply (compiler) {
|
|
|
|
const isBundledPage = /^bundles[/\\]pages.*\.js$/
|
|
|
|
const matchRouteName = /^bundles[/\\]pages[/\\](.*)\.js$/
|
|
|
|
|
|
|
|
compiler.plugin('after-compile', (compilation, callback) => {
|
|
|
|
const pages = Object
|
|
|
|
.keys(compilation.namedChunks)
|
|
|
|
.map(key => compilation.namedChunks[key])
|
|
|
|
.filter(chunk => isBundledPage.test(chunk.name))
|
|
|
|
|
|
|
|
pages.forEach((chunk) => {
|
|
|
|
const page = compilation.assets[chunk.name]
|
|
|
|
const pageName = matchRouteName.exec(chunk.name)[1]
|
2017-04-05 06:45:39 +00:00
|
|
|
const routeName = `/${pageName.replace(/[/\\]?index$/, '')}`
|
2017-04-03 18:10:24 +00:00
|
|
|
|
|
|
|
const content = page.source()
|
|
|
|
const newContent = `
|
2017-04-05 06:45:39 +00:00
|
|
|
function loadPage () {
|
|
|
|
var comp = ${content}
|
2017-04-06 05:26:13 +00:00
|
|
|
window.__NEXT_PAGE_LOADER__.registerPage('${routeName}', null, comp.default)
|
2017-04-05 06:45:39 +00:00
|
|
|
}
|
|
|
|
|
2017-04-06 05:26:13 +00:00
|
|
|
if (window.__NEXT_PAGE_LOADER__) {
|
2017-04-05 06:45:39 +00:00
|
|
|
loadPage()
|
|
|
|
} else {
|
2017-04-06 05:28:04 +00:00
|
|
|
window.__NEXT_LOADED_PAGES__ = window.__NEXT_LOADED_PAGES__ || []
|
|
|
|
window.__NEXT_LOADED_PAGES__.push(loadPage)
|
2017-04-05 06:45:39 +00:00
|
|
|
}
|
2017-04-03 18:10:24 +00:00
|
|
|
`
|
2017-04-06 05:03:11 +00:00
|
|
|
// Replace the exisiting chunk with the new content
|
|
|
|
compilation.assets[chunk.name] = {
|
2017-04-03 18:10:24 +00:00
|
|
|
source: () => newContent,
|
|
|
|
size: () => newContent.length
|
|
|
|
}
|
|
|
|
})
|
|
|
|
callback()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|