refacto: Hooks

This commit is contained in:
Atinux 2017-10-30 18:41:22 +01:00
parent 83815de91b
commit 6648695015
5 changed files with 85 additions and 76 deletions

View File

@ -57,6 +57,9 @@ export default class Builder extends Tapable {
this.vueLoader = vueLoaderConfig.bind(this)
this._buildStatus = STATUS.INITIAL
// Call class hook
this.nuxt.applyPlugins('builder', this)
}
get plugins() {
@ -119,7 +122,7 @@ export default class Builder extends Tapable {
await this.nuxt.ready()
// Wait for build plugins
await this.nuxt.applyPluginsAsync('build', this)
await this.applyPluginsAsync('build', this.options.build)
// Babel options
this.babelOptions = _.defaults(this.options.build.babel, {
@ -177,11 +180,11 @@ export default class Builder extends Tapable {
// Start webpack build
await this.webpackBuild()
await this.applyPluginsAsync('built', this)
// Flag to set that building is done
this._buildStatus = STATUS.BUILD_DONE
await this.applyPluginsAsync('built')
return this
}
@ -264,7 +267,7 @@ export default class Builder extends Tapable {
templateVars.router.routes = this.options.build.createRoutes(this.options.srcDir)
}
await this.applyPluginsAsync('extendRoutes', { routes: templateVars.router.routes, templateVars, r })
await this.applyPluginsAsync('extendRoutes', templateVars.router.routes)
// router.extendRoutes method
if (typeof this.options.router.extendRoutes === 'function') {
@ -332,7 +335,7 @@ export default class Builder extends Tapable {
}
}
await this.applyPluginsAsync('generate', { builder: this, templatesFiles, templateVars })
await this.applyPluginsAsync('generate', { templatesFiles, templateVars, resolve: r })
// Interpret and move template files to .nuxt/
await Promise.all(templatesFiles.map(async ({ src, dst, options, custom }) => {
@ -372,7 +375,7 @@ export default class Builder extends Tapable {
return utimes(path, dateFS, dateFS)
}))
await this.applyPluginsAsync('generated', this)
await this.applyPluginsAsync('generated')
}
async webpackBuild() {
@ -433,11 +436,11 @@ export default class Builder extends Tapable {
// Start Builds
await sequence(this.compilers, (compiler) => new Promise(async (resolve, reject) => {
const name = compiler.options.name
await this.applyPluginsAsync('compile', { builder: this, compiler, name })
await this.applyPluginsAsync('compile', { name, compiler })
// Resolve only when compiler emit done event
compiler.plugin('done', async (stats) => {
await this.applyPluginsAsync('compiled', { builder: this, compiler, name, stats })
await this.applyPluginsAsync('compiled', { name, compiler, stats })
process.nextTick(resolve)
})
// --- Dev Build ---

View File

@ -20,6 +20,9 @@ export default class Generator extends Tapable {
this.srcBuiltPath = resolve(this.options.buildDir, 'dist')
this.distPath = resolve(this.options.rootDir, this.options.generate.dir)
this.distNuxtPath = join(this.distPath, (isUrl(this.options.build.publicPath) ? '' : this.options.build.publicPath))
// Call class hook
this.nuxt.applyPlugins('generator', this)
}
async generate({ build = true, init = true } = {}) {
@ -50,10 +53,8 @@ export default class Generator extends Tapable {
try {
console.log('Generating routes') // eslint-disable-line no-console
generateRoutes = await promisifyRoute(this.options.generate.routes || [])
await this.applyPluginsAsync('generateRoutes', { generator: this, generateRoutes })
} catch (e) {
console.error('Could not resolve routes') // eslint-disable-line no-console
console.error(e) // eslint-disable-line no-console
throw e // eslint-disable-line no-unreachable
}
}
@ -62,7 +63,7 @@ export default class Generator extends Tapable {
let routes = (this.options.router.mode === 'hash') ? ['/'] : flatRoutes(this.options.router.routes)
routes = this.decorateWithPayloads(routes, generateRoutes)
await this.applyPluginsAsync('generate', { generator: this, routes })
await this.applyPluginsAsync('generate', routes)
// Start generate process
while (routes.length) {
@ -86,6 +87,8 @@ export default class Generator extends Tapable {
const duration = Math.round((Date.now() - s) / 100) / 10
debug(`HTML Files generated in ${duration}s`)
await this.applyPluginsAsync('generated', errors)
if (errors.length) {
const report = errors.map(({ type, route, error }) => {
/* istanbul ignore if */
@ -98,8 +101,6 @@ export default class Generator extends Tapable {
console.error('==== Error report ==== \n' + report.join('\n\n')) // eslint-disable-line no-console
}
await this.applyPluginsAsync('generated', this)
return { duration, errors }
}
@ -148,7 +149,7 @@ export default class Generator extends Tapable {
})
// Fill routeMap with given generate.routes
generateRoutes.forEach((route) => {
// route is either a string or like {route : "/my_route/1"}
// route is either a string or like { route : '/my_route/1', payload: {} }
const path = _.isString(route) ? route : route.route
routeMap[path] = {
route: path,

View File

@ -14,11 +14,16 @@ export default class ModuleContainer extends Tapable {
this.nuxt = nuxt
this.options = nuxt.options
this.requiredModules = []
// Call class hook
console.log('call module container')
this.nuxt.applyPlugins('moduleContainer', this)
}
async _ready () {
async ready() {
// Load every module in sequence
await sequence(this.options.modules, this.addModule.bind(this))
await this.applyPluginsAsync('ready', this)
await this.applyPluginsAsync('ready')
}
addVendor(vendor) {
@ -88,8 +93,6 @@ export default class ModuleContainer extends Tapable {
return
}
await this.applyPluginsAsync('add', {moduleOpts, requireOnce})
// Allow using babel style array options
if (Array.isArray(moduleOpts)) {
moduleOpts = {
@ -129,13 +132,13 @@ export default class ModuleContainer extends Tapable {
}
// Call module with `this` context and pass options
return new Promise((resolve, reject) => {
const result = module.call(this, options, err => {
const m = await new Promise((resolve, reject) => {
const result = module.call(this, options, (err, m) => {
/* istanbul ignore if */
if (err) {
return reject(err)
}
resolve(module)
resolve(m)
})
// If module send back a promise
if (result && result.then instanceof Function) {
@ -146,5 +149,6 @@ export default class ModuleContainer extends Tapable {
return resolve(module)
}
})
await this.applyPluginsAsync('module', { meta: module.meta, module: m })
}
}

View File

@ -12,10 +12,10 @@ const debug = Debug('nuxt:')
debug.color = 5
export default class Nuxt extends Tapable {
constructor (_options = {}) {
constructor(options = {}) {
super()
this.options = Options.from(_options)
this.options = Options.from(options)
// Paths for resolving requires from `rootDir`
this.nodeModulePaths = Module._nodeModulePaths(this.options.rootDir)
@ -40,9 +40,9 @@ export default class Nuxt extends Tapable {
return this._ready
}
await this.moduleContainer._ready()
await this.moduleContainer.ready()
await this.applyPluginsAsync('ready')
await this.renderer._ready()
await this.renderer.ready()
this.initialized = true
return this

View File

@ -49,11 +49,12 @@ export default class Renderer extends Tapable {
spaTemplate: null,
errorTemplate: parseTemplate('Nuxt.js Internal Server Error')
}
// Call class hook
this.nuxt.applyPlugins('renderer', this)
}
async _ready () {
await this.nuxt.applyPluginsAsync('renderer', this)
async ready() {
// Setup nuxt middleware
await this.setupMiddleware()
@ -63,7 +64,7 @@ export default class Renderer extends Tapable {
}
// Call ready plugin
await this.applyPluginsAsync('ready', this)
await this.applyPluginsAsync('ready')
}
async loadResources(_fs = fs) {
@ -283,6 +284,7 @@ export default class Renderer extends Tapable {
async nuxtMiddleware(req, res, next) {
// Get context
const context = getContext(req, res)
res.statusCode = 200
try {
const { html, error, redirected, resourceHints } = await this.renderRoute(req.url, context)
@ -563,8 +565,7 @@ export default class Renderer extends Tapable {
runScripts: 'dangerously',
beforeParse(window) {
// Mock window.scrollTo
window.scrollTo = () => {
}
window.scrollTo = () => {}
}
}
if (opts.virtualConsole !== false) {