Nuxt/lib/builder/generator.js

217 lines
6.4 KiB
JavaScript
Raw Normal View History

import { copy, remove, writeFile, mkdirp, removeSync, existsSync } from 'fs-extra'
2017-01-11 19:14:59 +00:00
import _ from 'lodash'
import { resolve, join, dirname, sep } from 'path'
import { minify } from 'html-minifier'
2017-06-16 12:42:45 +00:00
import { isUrl, promisifyRoute, waitFor, flatRoutes } from 'utils'
2016-11-10 11:33:52 +00:00
2017-10-30 21:39:08 +00:00
export default class Generator {
2017-10-30 17:41:22 +00:00
constructor(nuxt, builder) {
2017-06-11 14:17:36 +00:00
this.nuxt = nuxt
this.options = nuxt.options
this.builder = builder
2017-07-03 11:11:40 +00:00
// Set variables
this.staticRoutes = resolve(this.options.srcDir, 'static')
2017-07-03 11:11:40 +00:00
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))
}
2017-06-11 14:17:36 +00:00
2017-10-30 17:41:22 +00:00
async generate({ build = true, init = true } = {}) {
await this.initiate({ build, init })
const routes = await this.initRoutes()
const errors = await this.generateRoutes(routes)
await this.afterGenerate()
// done hook
await this.nuxt.callHook('generate:done', this, errors)
return { errors }
}
async initiate({ build = true, init = true } = {}) {
2017-10-30 21:39:08 +00:00
// Wait for nuxt be ready
await this.nuxt.ready()
// Call before hook
await this.nuxt.callHook('generate:before', this, this.options.generate)
2017-08-18 13:46:48 +00:00
// Add flag to set process.static
2017-08-18 13:27:58 +00:00
this.builder.forGenerate()
// Start build process
2017-08-17 12:43:51 +00:00
if (build) {
await this.builder.build()
}
// Initialize dist directory
if (init) {
await this.initDist()
2017-06-11 14:17:36 +00:00
}
}
2017-06-12 20:16:42 +00:00
async initRoutes(...args) {
2017-06-12 20:16:42 +00:00
// Resolve config.generate.routes promises before generating the routes
let generateRoutes = []
2017-06-11 14:17:36 +00:00
if (this.options.router.mode !== 'hash') {
2017-05-14 18:21:14 +00:00
try {
generateRoutes = await promisifyRoute(this.options.generate.routes || [], ...args)
2017-06-11 14:17:36 +00:00
} catch (e) {
console.error('Could not resolve routes') // eslint-disable-line no-console
throw e // eslint-disable-line no-unreachable
2016-11-24 00:47:11 +00:00
}
2017-06-11 14:17:36 +00:00
}
2017-06-12 20:16:42 +00:00
// 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)
2017-06-11 14:17:36 +00:00
2017-10-30 21:39:08 +00:00
// extendRoutes hook
await this.nuxt.callHook('generate:extendRoutes', routes)
2017-07-03 11:11:40 +00:00
return routes
}
async generateRoutes(routes) {
let errors = []
// Start generate process
2017-06-11 14:17:36 +00:00
while (routes.length) {
let n = 0
2017-07-09 10:00:08 +00:00
await Promise.all(routes.splice(0, this.options.generate.concurrency).map(async ({ route, payload }) => {
2017-06-11 14:17:36 +00:00
await waitFor(n++ * this.options.generate.interval)
await this.generateRoute({ route, payload, errors })
2017-06-11 14:17:36 +00:00
}))
}
2017-06-12 20:16:42 +00:00
return errors
}
async afterGenerate() {
2017-10-23 21:43:59 +00:00
const indexPath = join(this.distPath, 'index.html')
2017-10-25 11:27:51 +00:00
if (existsSync(indexPath)) {
2017-10-23 21:43:59 +00:00
// Copy /index.html to /200.html for surge SPA
// https://surge.sh/help/adding-a-200-page-for-client-side-routing
const _200Path = join(this.distPath, '200.html')
if (!existsSync(_200Path)) {
await copy(indexPath, _200Path)
}
}
}
2017-10-30 17:41:22 +00:00
async initDist() {
// Clean destination folder
await remove(this.distPath)
await this.nuxt.callHook('generate:distRemoved', this)
// Copy static and built files
/* istanbul ignore if */
if (existsSync(this.staticRoutes)) {
await copy(this.staticRoutes, 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, '')
// Cleanup SSR related files
const extraFiles = [
'index.spa.html',
'index.ssr.html',
'server-bundle.json',
'vue-ssr-client-manifest.json'
].map(file => resolve(this.distNuxtPath, file))
extraFiles.forEach(file => {
if (existsSync(file)) {
removeSync(file)
}
})
await this.nuxt.callHook('generate:distCopied', this)
}
2017-10-30 17:41:22 +00:00
decorateWithPayloads(routes, generateRoutes) {
let routeMap = {}
// Fill routeMap for known routes
routes.forEach((route) => {
routeMap[route] = {
route,
payload: null
}
})
// Fill routeMap with given generate.routes
generateRoutes.forEach((route) => {
2017-10-30 17:41:22 +00:00
// route is either a string or like { route : '/my_route/1', payload: {} }
const path = _.isString(route) ? route : route.route
routeMap[path] = {
route: path,
payload: route.payload || null
}
})
return _.values(routeMap)
}
2017-10-30 17:41:22 +00:00
async generateRoute({ route, payload = {}, errors = [] }) {
let html
const pageErrors = []
try {
const res = await this.nuxt.renderer.renderRoute(route, { _generate: true, payload })
html = res.html
if (res.error) {
pageErrors.push({ type: 'handled', route, error: res.error })
}
} catch (err) {
/* istanbul ignore next */
pageErrors.push({ type: 'unhandled', route, error: err })
Array.prototype.push.apply(errors, pageErrors)
await this.nuxt.callHook('generate:routeFailed', { route, errors: pageErrors })
return false
}
if (this.options.generate.minify) {
try {
html = minify(html, this.options.generate.minify)
} catch (err) /* istanbul ignore next */ {
const minifyErr = new Error(`HTML minification failed. Make sure the route generates valid HTML. Failed HTML:\n ${html}`)
pageErrors.push({ type: 'unhandled', route, error: minifyErr })
}
}
2017-11-06 07:36:28 +00:00
let path
if (this.options.generate.subFolders) {
path = join(route, sep, 'index.html') // /about -> /about/index.html
path = path === '/404/index.html' ? '/404.html' : path // /404 -> /404.html
} else {
path =
route.length > 1 ? join(sep, route + '.html') : join(sep, 'index.html')
}
2017-10-30 22:14:21 +00:00
// Call hook to let user update the path & html
const page = { route, path, html }
await this.nuxt.callHook('generate:page', page)
page.path = join(this.distPath, page.path)
// Make sure the sub folders are created
2017-10-30 22:14:21 +00:00
await mkdirp(dirname(page.path))
await writeFile(page.path, page.html, 'utf8')
await this.nuxt.callHook('generate:routeCreated', { route, path: page.path, errors: pageErrors })
if (pageErrors.length) {
Array.prototype.push.apply(errors, pageErrors)
}
return true
}
2016-11-10 11:33:52 +00:00
}