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

69 lines
1.9 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')
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)
.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 = [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)
if (name === errorPageName) {
compiler.addEntry([
hotMiddlewareClientPath,
errorPagePath
], 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
}
}