refactor: add hooks (#3772)

This commit is contained in:
Clark Du 2018-08-20 15:20:45 +01:00 committed by GitHub
parent 7b910428bc
commit b920f22483
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 17 additions and 24 deletions

View File

@ -59,7 +59,7 @@ export default class Nuxt {
// Add hooks
if (_.isPlainObject(this.options.hooks)) {
this.addObjectHooks(this.options.hooks)
this.addHooks(this.options.hooks)
} else if (typeof this.options.hooks === 'function') {
this.options.hooks(this.hook)
}
@ -105,30 +105,23 @@ export default class Nuxt {
}
}
getObjectHooks(hooksObj, keyList = [], stack = '') {
Object.keys(hooksObj).forEach((key) => {
if (typeof hooksObj[key] === 'object' && hooksObj[key] !== null) {
this.getObjectHooks(hooksObj[key], keyList, `${stack}:${key}`)
flatHooks(configHooks, hooks = {}, parentName) {
Object.keys(configHooks).forEach((key) => {
const subHook = configHooks[key]
const name = parentName ? `${parentName}:${key}` : key
if (typeof subHook === 'object' && subHook !== null) {
this.flatHooks(subHook, hooks, name)
} else {
const value = hooksObj[key]
key = `${stack}:${key}`
keyList.push({
name: key.slice(1),
hook: value
})
hooks[name] = subHook
}
})
return keyList.reduce((hash, pair) => {
return { ...hash, [pair.name]: pair.hook }
}, {})
return hooks
}
addObjectHooks(obj) {
const hooksObj = this.getObjectHooks(obj)
Object.keys(hooksObj).filter(Boolean).forEach((key) => {
const hook = hooksObj[key]
const hooks = Array.isArray(hook) ? hook : [hook]
hooks.forEach(h => this.hook(key, h))
addHooks(configHooks) {
const hooks = this.flatHooks(configHooks)
Object.keys(hooks).filter(Boolean).forEach((key) => {
[].concat(hooks[key]).forEach(h => this.hook(key, h))
})
}

View File

@ -42,11 +42,11 @@ export default {
modulesDir: path.join(__dirname, '..', '..', '..', 'node_modules'),
hooks: {
ready(nuxt) {
nuxt.__hook_called__ = true
nuxt.__hook_ready_called__ = true
},
build: {
done(builder) {
builder.__hook_called__ = true
builder.__hook_built_called__ = true
}
},
bad: null,

View File

@ -34,7 +34,7 @@ describe('basic dev', () => {
})
test('Check build:done hook called', () => {
expect(builder.__hook_called__).toBe(true)
expect(builder.__hook_built_called__).toBe(true)
})
test('Config: build.transpile', () => {

View File

@ -40,7 +40,7 @@ describe('basic generate', () => {
})
test('Check ready hook called', () => {
expect(generator.nuxt.__hook_called__).toBe(true)
expect(generator.nuxt.__hook_ready_called__).toBe(true)
})
test('Format errors', () => {