feat(generator): refactor generate into functions

This commit is contained in:
Pooya Parsa 2017-07-05 02:56:01 +04:30
parent 9475e1c431
commit 498c6be7a5
1 changed files with 86 additions and 66 deletions

View File

@ -26,34 +26,27 @@ export default class Generator extends Tapable {
this.nuxt.applyPluginsAsync('generator', this).catch(this.nuxt.errorHandler)
}
async generate (doBuild = true) {
async generate ({ build = true, init = true } = {}) {
const s = Date.now()
let errors = []
let generateRoutes = []
// Wait for nuxt be ready
await this.nuxt.ready()
// Start build process
if (this.builder && doBuild) {
if (this.builder && build) {
await this.builder.build()
}
await this.applyPluginsAsync('before-generate', this)
await this.applyPluginsAsync('beforeGenerate', this)
// Clean destination folder
await remove(this.distPath)
debug('Destination folder cleaned')
// Copy static and built files
/* istanbul ignore if */
if (fs.existsSync(this.generateRoutes)) {
await copy(this.generateRoutes, this.distPath)
// Initialize dist directory
if (init) {
await this.initDist()
}
await copy(this.srcBuiltPath, this.distNuxtPath)
debug('Static & build files copied')
// Resolve config.generate.routes promises before generating the routes
let generateRoutes = []
if (this.options.router.mode !== 'hash') {
try {
console.log('Generating routes') // eslint-disable-line no-console
@ -66,7 +59,62 @@ export default class Generator extends Tapable {
}
}
const decorateWithPayloads = (routes) => {
// Generate only index.html for router.mode = 'hash'
let routes = (this.options.router.mode === 'hash') ? ['/'] : flatRoutes(this.options.router.routes)
routes = this.decorateWithPayloads(routes, generateRoutes)
await this.applyPluginsAsync('generate', {generator: this, routes})
// Start generate process
while (routes.length) {
let n = 0
await Promise.all(routes.splice(0, 500).map(async ({ route, payload }) => {
await waitFor(n++ * this.options.generate.interval)
await this.generateRoute({route, payload, errors})
}))
}
const duration = Math.round((Date.now() - s) / 100) / 10
debug(`HTML Files generated in ${duration}s`)
if (errors.length) {
const report = errors.map(({ type, route, error }) => {
/* istanbul ignore if */
if (type === 'unhandled') {
return `Route: '${route}'\n${error.stack}`
} else {
return `Route: '${route}' thrown an error: \n` + JSON.stringify(error)
}
})
console.error('==== Error report ==== \n' + report.join('\n\n')) // eslint-disable-line no-console
}
await this.applyPluginsAsync('generated', this)
return { duration, errors }
}
async initDist () {
// Clean destination folder
await remove(this.distPath)
debug('Destination folder cleaned')
// Copy static and built files
/* istanbul ignore if */
if (fs.existsSync(this.generateRoutes)) {
await copy(this.generateRoutes, this.distPath)
}
await copy(this.srcBuiltPath, this.distNuxtPath)
// Add .nojekyll file to let Github Pages add the _nuxt/ folder
// https://help.github.com/articles/files-that-start-with-an-underscore-are-missing/
const nojekyllPath = resolve(this.distPath, '.nojekyll')
writeFile(nojekyllPath, '')
debug('Static & build files copied')
}
decorateWithPayloads (routes, generateRoutes) {
let routeMap = {}
// Fill routeMap for known routes
routes.forEach((route) => {
@ -87,17 +135,9 @@ export default class Generator extends Tapable {
return _.values(routeMap)
}
// Generate only index.html for router.mode = 'hash'
let routes = (this.options.router.mode === 'hash') ? ['/'] : flatRoutes(this.options.router.routes)
routes = decorateWithPayloads(routes)
await this.applyPluginsAsync('generate', {generator: this, routes})
while (routes.length) {
let n = 0
await Promise.all(routes.splice(0, 500).map(async ({ route, payload }) => {
await waitFor(n++ * this.options.generate.interval)
async generateRoute ({route, payload = {}, errors = []}) {
let html
try {
const res = await this.nuxt.renderer.renderRoute(route, { _generate: true, payload })
html = res.html
@ -108,6 +148,7 @@ export default class Generator extends Tapable {
/* istanbul ignore next */
return errors.push({ type: 'unhandled', route, error: err })
}
if (this.options.generate.minify) {
try {
html = minify(html, this.options.generate.minify)
@ -116,37 +157,16 @@ export default class Generator extends Tapable {
errors.push({ type: 'unhandled', route, error: minifyErr })
}
}
let path = join(route, sep, 'index.html') // /about -> /about/index.html
path = (path === '/404/index.html') ? '/404.html' : path // /404 -> /404.html
debug('Generate file: ' + path)
path = join(this.distPath, path)
// Make sure the sub folders are created
await mkdirp(dirname(path))
await writeFile(path, html, 'utf8')
}))
}
// Add .nojekyll file to let Github Pages add the _nuxt/ folder
// https://help.github.com/articles/files-that-start-with-an-underscore-are-missing/
const nojekyllPath = resolve(this.distPath, '.nojekyll')
writeFile(nojekyllPath, '')
const duration = Math.round((Date.now() - s) / 100) / 10
debug(`HTML Files generated in ${duration}s`)
if (errors.length) {
const report = errors.map(({ type, route, error }) => {
/* istanbul ignore if */
if (type === 'unhandled') {
return `Route: '${route}'\n${error.stack}`
} else {
return `Route: '${route}' thrown an error: \n` + JSON.stringify(error)
}
})
console.error('==== Error report ==== \n' + report.join('\n\n')) // eslint-disable-line no-console
}
await this.applyPluginsAsync('generated', this)
return { duration, errors }
return true
}
}