Skip to content

Commit

Permalink
refacto: Hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
Atinux committed Oct 30, 2017
1 parent 83815de commit 6648695
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 76 deletions.
39 changes: 21 additions & 18 deletions lib/builder/builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ debug.color = 2 // Force green color
const glob = pify(Glob)

export default class Builder extends Tapable {
constructor (nuxt) {
constructor(nuxt) {
super()
this.nuxt = nuxt
this.isStatic = false // Flag to know if the build is for a generated app
Expand Down Expand Up @@ -57,9 +57,12 @@ 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 () {
get plugins() {
return this.options.plugins.map((p, i) => {
if (typeof p === 'string') p = { src: p }
return {
Expand All @@ -70,7 +73,7 @@ export default class Builder extends Tapable {
})
}

vendor () {
vendor() {
return [
'vue',
'vue-router',
Expand All @@ -79,7 +82,7 @@ export default class Builder extends Tapable {
].concat(this.options.build.vendor).filter(v => v)
}

vendorEntries () {
vendorEntries() {
// Used for dll
const vendor = this.vendor()
const vendorEntries = {}
Expand All @@ -94,11 +97,11 @@ export default class Builder extends Tapable {
return vendorEntries
}

forGenerate () {
forGenerate() {
this.isStatic = true
}

async build () {
async build() {
// Avoid calling build() method multiple times when dev:true
/* istanbul ignore if */
if (this._buildStatus === STATUS.BUILD_DONE && this.options.dev) {
Expand All @@ -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, {
Expand Down Expand Up @@ -177,15 +180,15 @@ 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
}

async generateRoutesAndFiles () {
async generateRoutesAndFiles() {
debug('Generating files...')
// -- Templates --
let templatesFiles = [
Expand Down Expand Up @@ -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') {
Expand Down Expand Up @@ -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 }) => {
Expand Down Expand Up @@ -372,10 +375,10 @@ export default class Builder extends Tapable {
return utimes(path, dateFS, dateFS)
}))

await this.applyPluginsAsync('generated', this)
await this.applyPluginsAsync('generated')
}

async webpackBuild () {
async webpackBuild() {
debug('Building files...')
const compilersOptions = []

Expand Down Expand Up @@ -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 ---
Expand Down Expand Up @@ -484,7 +487,7 @@ export default class Builder extends Tapable {
}
}

webpackDev (compiler) {
webpackDev(compiler) {
debug('Adding webpack middleware...')

// Create webpack dev middleware
Expand Down Expand Up @@ -516,7 +519,7 @@ export default class Builder extends Tapable {
this.watchFiles()
}

watchFiles () {
watchFiles() {
const patterns = [
r(this.options.srcDir, 'layouts'),
r(this.options.srcDir, 'store'),
Expand Down
23 changes: 12 additions & 11 deletions lib/builder/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Debug from 'debug'
const debug = Debug('nuxt:generate')

export default class Generator extends Tapable {
constructor (nuxt, builder) {
constructor(nuxt, builder) {
super()
this.nuxt = nuxt
this.options = nuxt.options
Expand All @@ -20,9 +20,12 @@ 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 } = {}) {
async generate({ build = true, init = true } = {}) {
const s = Date.now()
let errors = []

Expand Down Expand Up @@ -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
}
}
Expand All @@ -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) {
Expand All @@ -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 */
Expand All @@ -98,12 +101,10 @@ 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 }
}

async initDist () {
async initDist() {
// Clean destination folder
await remove(this.distPath)
debug('Destination folder cleaned')
Expand Down Expand Up @@ -137,7 +138,7 @@ export default class Generator extends Tapable {
debug('Static & build files copied')
}

decorateWithPayloads (routes, generateRoutes) {
decorateWithPayloads(routes, generateRoutes) {
let routeMap = {}
// Fill routeMap for known routes
routes.forEach((route) => {
Expand All @@ -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,
Expand All @@ -158,7 +159,7 @@ export default class Generator extends Tapable {
return _.values(routeMap)
}

async generateRoute ({ route, payload = {}, errors = [] }) {
async generateRoute({ route, payload = {}, errors = [] }) {
let html

try {
Expand Down
36 changes: 20 additions & 16 deletions lib/core/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,32 @@ import Debug from 'debug'
const debug = Debug('nuxt:module')

export default class ModuleContainer extends Tapable {
constructor (nuxt) {
constructor(nuxt) {
super()
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) {
addVendor(vendor) {
/* istanbul ignore if */
if (!vendor) {
return
}
this.options.build.vendor = uniq(this.options.build.vendor.concat(vendor))
}

addTemplate (template) {
addTemplate(template) {
/* istanbul ignore if */
if (!template) {
return
Expand All @@ -56,7 +61,7 @@ export default class ModuleContainer extends Tapable {
return templateObj
}

addPlugin (template) {
addPlugin(template) {
const { dst } = this.addTemplate(template)
// Add to nuxt plugins
this.options.plugins.unshift({
Expand All @@ -65,31 +70,29 @@ export default class ModuleContainer extends Tapable {
})
}

addServerMiddleware (middleware) {
addServerMiddleware(middleware) {
this.options.serverMiddleware.push(middleware)
}

extendBuild (fn) {
extendBuild(fn) {
this.options.build.extend = chainFn(this.options.build.extend, fn)
}

extendRoutes (fn) {
extendRoutes(fn) {
this.options.router.extendRoutes = chainFn(this.options.router.extendRoutes, fn)
}

requireModule (moduleOpts) {
requireModule(moduleOpts) {
// Require once
return this.addModule(moduleOpts, true)
}

async addModule (moduleOpts, requireOnce) {
async addModule(moduleOpts, requireOnce) {
/* istanbul ignore if */
if (!moduleOpts) {
return
}

await this.applyPluginsAsync('add', {moduleOpts, requireOnce})

// Allow using babel style array options
if (Array.isArray(moduleOpts)) {
moduleOpts = {
Expand Down Expand Up @@ -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) {
Expand All @@ -146,5 +149,6 @@ export default class ModuleContainer extends Tapable {
return resolve(module)
}
})
await this.applyPluginsAsync('module', { meta: module.meta, module: m })
}
}

0 comments on commit 6648695

Please sign in to comment.