1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/server/build/plugins/pages-plugin.js
2017-04-05 12:15:39 +05:30

44 lines
1.4 KiB
JavaScript

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]
const routeName = `/${pageName.replace(/[/\\]?index$/, '')}`
const content = page.source()
const newContent = `
function loadPage () {
var comp = ${content}
window.NEXT_PAGE_LOADER.registerPage('${routeName}', null, comp.default)
}
if (window.NEXT_PAGE_LOADER) {
loadPage()
} else {
window.NEXT_LOADED_PAGES = window.NEXT_LOADED_PAGES || []
window.NEXT_LOADED_PAGES.push(loadPage)
}
`
// Replace the current asset
// TODO: We need to move "client-bundles" back to "bundles" once we remove
// all the JSON eval stuff
delete compilation.assets[chunk.name]
compilation.assets[`client-bundles/pages/${pageName}.js`] = {
source: () => newContent,
size: () => newContent.length
}
})
callback()
})
}
}