Skip to content

Commit

Permalink
feat(cli): prevent reload when config is overwritten
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 19, 2022
1 parent 80b3ea1 commit 0c7f947
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
10 changes: 7 additions & 3 deletions packages/cli/src/addons/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ function unwrap(module: any) {
const logger = new Logger('watch')

export default class FileWatcher extends Service {
public suspend = false

private root: string
private watcher: FSWatcher
private currentUpdate: Promise<void[]>
Expand Down Expand Up @@ -62,11 +64,14 @@ export default class FileWatcher extends Service {
}

this.watcher.on('change', (path) => {
if (!require.cache[path]) return
if (this.suspend) return
logger.debug('change detected:', path)

const isEntry = path === this.ctx.app.loader.filename
if (!require.cache[path] && !isEntry) return

// files independent from any plugins will trigger a full reload
if (path === this.ctx.app.loader.filename || this.externals.has(path)) {
if (isEntry || this.externals.has(path)) {
return triggerFullReload()
}

Expand Down Expand Up @@ -190,7 +195,6 @@ export default class FileWatcher extends Service {

// delete module cache before re-require
accepted.forEach((path) => {
logger.debug('cache deleted:', path)
delete require.cache[path]
})

Expand Down
4 changes: 4 additions & 0 deletions packages/cli/src/addons/writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ export default class ConfigWriter extends Service {

writeConfig() {
if (!this.allowWrite) return
// prevent hot reload when it's being written
const fileWatcher = this.ctx.fileWatcher
fileWatcher && (fileWatcher.suspend = true)
writeFileSync(this.loader.filename, dump(this.config))
fileWatcher && (fileWatcher.suspend = false)
}

async loadPlugin(name: string, config: any) {
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ export class Loader {
loadConfig(): App.Config {
if (['.yaml', '.yml'].includes(this.extname)) {
return load(readFileSync(this.filename, 'utf8')) as any
} else if (['.json'].includes(this.extname)) {
// we do not use require here because it will pollute require.cache
return JSON.parse(readFileSync(this.filename, 'utf8')) as any
} else {
const module = require(this.filename)
return module.default || module
Expand Down

0 comments on commit 0c7f947

Please sign in to comment.