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/watch-pages-plugin.js

65 lines
1.7 KiB
JavaScript
Raw Normal View History

2016-10-23 16:42:13 +00:00
import { resolve, relative, join, extname } from 'path'
export default class WatchPagesPlugin {
constructor (dir) {
this.dir = resolve(dir, 'pages')
this.prevFileDependencies = null
2016-10-23 16:42:13 +00:00
}
apply (compiler) {
compiler.plugin('emit', (compilation, callback) => {
// watch the pages directory
compilation.contextDependencies =
compilation.contextDependencies.concat([this.dir])
this.prevFileDependencies = compilation.fileDependencies
2016-10-23 16:42:13 +00:00
callback()
})
const isPageFile = this.isPageFile.bind(this)
const getEntryName = (f) => {
return join('bundles', relative(compiler.options.context, f))
}
const errorPageName = join('bundles', 'pages', '_error.js')
2016-10-23 16:42:13 +00:00
compiler.plugin('watch-run', (watching, callback) => {
Object.keys(compiler.fileTimestamps)
.filter(isPageFile)
.filter((f) => this.prevFileDependencies.indexOf(f) < 0)
2016-10-23 16:42:13 +00:00
.forEach((f) => {
const name = getEntryName(f)
if (name === errorPageName) {
compiler.removeEntry(name)
}
2016-10-23 16:42:13 +00:00
if (compiler.hasEntry(name)) return
const entries = ['webpack/hot/dev-server', f]
2016-10-23 16:42:13 +00:00
compiler.addEntry(entries, name)
})
compiler.removedFiles
.filter(isPageFile)
.forEach((f) => {
const name = getEntryName(f)
compiler.removeEntry(name)
if (name === errorPageName) {
compiler.addEntry([
'webpack/hot/dev-server',
join(__dirname, '..', '..', '..', 'pages', '_error.js')
], name)
}
2016-10-23 16:42:13 +00:00
})
callback()
})
}
isPageFile (f) {
return f.indexOf(this.dir) === 0 && extname(f) === '.js'
}
}