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')
|
2016-11-03 15:12:37 +00:00
|
|
|
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])
|
|
|
|
|
2016-11-03 15:12:37 +00:00
|
|
|
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))
|
|
|
|
}
|
2016-11-03 15:12:37 +00:00
|
|
|
const errorPageName = join('bundles', 'pages', '_error.js')
|
2016-12-16 20:33:08 +00:00
|
|
|
const errorPagePath = join(__dirname, '..', '..', '..', 'pages', '_error.js')
|
|
|
|
const hotMiddlewareClientPath = join(__dirname, '..', '..', '..', 'client/webpack-hot-middleware-client')
|
2016-10-23 16:42:13 +00:00
|
|
|
|
|
|
|
compiler.plugin('watch-run', (watching, callback) => {
|
|
|
|
Object.keys(compiler.fileTimestamps)
|
|
|
|
.filter(isPageFile)
|
2016-11-03 15:12:37 +00:00
|
|
|
.filter((f) => this.prevFileDependencies.indexOf(f) < 0)
|
2016-10-23 16:42:13 +00:00
|
|
|
.forEach((f) => {
|
|
|
|
const name = getEntryName(f)
|
2016-11-03 15:12:37 +00:00
|
|
|
if (name === errorPageName) {
|
|
|
|
compiler.removeEntry(name)
|
|
|
|
}
|
|
|
|
|
2016-10-23 16:42:13 +00:00
|
|
|
if (compiler.hasEntry(name)) return
|
|
|
|
|
2016-12-16 20:33:08 +00:00
|
|
|
const entries = [hotMiddlewareClientPath, 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)
|
2016-11-03 15:12:37 +00:00
|
|
|
|
|
|
|
if (name === errorPageName) {
|
|
|
|
compiler.addEntry([
|
2016-12-16 20:33:08 +00:00
|
|
|
hotMiddlewareClientPath,
|
|
|
|
errorPagePath
|
2016-11-03 15:12:37 +00:00
|
|
|
], name)
|
|
|
|
}
|
2016-10-23 16:42:13 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
callback()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
isPageFile (f) {
|
2016-12-16 18:42:40 +00:00
|
|
|
return f.indexOf(this.dir) === 0 &&
|
|
|
|
relative(this.dir, f) !== '_document.js' &&
|
|
|
|
extname(f) === '.js'
|
2016-10-23 16:42:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|