Nuxt/lib/render.js

197 lines
6.6 KiB
JavaScript
Raw Permalink Normal View History

2017-01-11 19:14:59 +00:00
'use strict'
import ansiHTML from 'ansi-html'
import serialize from 'serialize-javascript'
2017-05-21 12:18:21 +00:00
import generateETag from 'etag'
import fresh from 'fresh'
import { getContext, setAnsiColors, encodeHtml } from './utils'
2017-06-05 08:57:41 +00:00
2017-03-20 16:52:35 +00:00
const debug = require('debug')('nuxt:render')
2017-01-11 19:14:59 +00:00
// force blue color
debug.color = 4
setAnsiColors(ansiHTML)
2016-11-28 15:44:38 +00:00
export async function render (req, res) {
// Wait for nuxt.js to be ready
await this.ready()
// Check if project is built for production
2016-12-07 18:02:06 +00:00
if (!this.renderer && !this.dev) {
2016-12-08 15:41:20 +00:00
console.error('> No build files found, please run `nuxt build` before launching `nuxt start`') // eslint-disable-line no-console
2016-12-07 18:02:06 +00:00
process.exit(1)
}
2016-12-20 18:26:01 +00:00
/* istanbul ignore if */
if (!this.renderer || !this.appTemplate) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(this.render(req, res))
}, 1000)
})
2016-11-28 15:44:38 +00:00
}
// Get context
2016-11-28 15:44:38 +00:00
const context = getContext(req, res)
res.statusCode = 200
try {
2017-05-17 09:27:05 +00:00
if (this.dev) {
2017-02-03 14:09:27 +00:00
// Call webpack middleware only in development
2017-05-17 09:27:05 +00:00
await this.webpackDevMiddleware(req, res)
await this.webpackHotMiddleware(req, res)
2017-02-21 17:39:29 +00:00
}
2017-05-21 12:06:01 +00:00
if (!this.dev && this.options.render.gzip) {
2017-05-17 09:27:05 +00:00
await this.gzipMiddleware(req, res)
2016-11-28 15:44:38 +00:00
}
2017-02-03 14:09:27 +00:00
// If base in req.url, remove it for the middleware and vue-router
2017-05-17 09:27:05 +00:00
if (this.options.router.base !== '/' && req.url.indexOf(this.options.router.base) === 0) {
2016-11-28 15:44:38 +00:00
// Compatibility with base url for dev server
2017-05-17 09:27:05 +00:00
req.url = req.url.replace(this.options.router.base, '/')
2016-11-28 15:44:38 +00:00
}
// Serve static/ files
2017-05-17 09:27:05 +00:00
await this.serveStatic(req, res)
2016-11-28 15:44:38 +00:00
// Serve .nuxt/dist/ files (only for production)
2017-05-17 09:27:05 +00:00
if (!this.dev && req.url.indexOf(this.options.build.publicPath) === 0) {
2016-11-28 15:44:38 +00:00
const url = req.url
2017-05-17 09:27:05 +00:00
req.url = req.url.replace(this.options.build.publicPath, '/')
await this.serveStaticNuxt(req, res)
2016-12-21 14:03:23 +00:00
/* istanbul ignore next */
2016-11-28 15:44:38 +00:00
req.url = url
}
2017-05-17 09:27:05 +00:00
if (this.dev && req.url.indexOf(this.options.build.publicPath) === 0 && req.url.includes('.hot-update.json')) {
2016-11-28 15:44:38 +00:00
res.statusCode = 404
2017-05-16 13:12:30 +00:00
return res.end()
2016-11-28 15:44:38 +00:00
}
2017-06-05 08:57:41 +00:00
const {html, error, redirected, resourceHints} = await this.renderRoute(req.url, context)
2017-02-22 18:19:17 +00:00
if (redirected) {
return html
}
2016-11-28 15:44:38 +00:00
if (error) {
res.statusCode = context.nuxt.error.statusCode || 500
}
2017-05-21 15:03:21 +00:00
// ETag header
2017-05-21 12:18:21 +00:00
if (!error && this.options.render.etag) {
const etag = generateETag(html, this.options.render.etag)
2017-06-05 08:57:41 +00:00
if (fresh(req.headers, {etag})) {
2017-05-21 12:18:21 +00:00
res.statusCode = 304
res.end()
return
}
res.setHeader('ETag', etag)
}
// HTTP2 push headers
2017-06-05 08:57:41 +00:00
if (!error && this.options.render.http2.push) {
// Parse resourceHints to extract HTTP.2 prefetch/push headers
// https://w3c.github.io/preload/#server-push-http-2
const regex = /link rel="([^"]*)" href="([^"]*)" as="([^"]*)"/g
const pushAssets = []
let m
while (m = regex.exec(resourceHints)) { // eslint-disable-line no-cond-assign
const [_, rel, href, as] = m // eslint-disable-line no-unused-vars
if (rel === 'preload') {
pushAssets.push(`<${href}>; rel=${rel}; as=${as}`)
}
2017-05-21 15:03:21 +00:00
}
// Pass with single Link header
// https://blog.cloudflare.com/http-2-server-push-with-multiple-assets-per-link-header
res.setHeader('Link', pushAssets.join(','))
2017-05-21 15:03:21 +00:00
}
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.setHeader('Content-Length', Buffer.byteLength(html))
2016-11-28 15:44:38 +00:00
res.end(html, 'utf8')
return html
} catch (err) {
2017-03-26 21:38:51 +00:00
if (context.redirected) {
console.error(err) // eslint-disable-line no-console
return err
}
const html = this.errorTemplate({
2017-06-05 08:57:41 +00:00
/* istanbul ignore if */
error: err,
stack: ansiHTML(encodeHtml(err.stack))
})
2016-11-28 15:44:38 +00:00
res.statusCode = 500
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.setHeader('Content-Length', Buffer.byteLength(html))
res.end(html, 'utf8')
return err
}
2016-11-28 15:44:38 +00:00
}
export async function renderRoute (url, context = {}) {
// Wait for modules to be initialized
await this.ready()
// Log rendered url
2016-11-28 15:44:38 +00:00
debug(`Rendering url ${url}`)
// Add url and isSever to the context
context.url = url
context.isServer = true
2017-05-05 14:48:04 +00:00
// Call renderToString from the bundleRenderer and generate the HTML (will update the context as well)
2017-05-17 09:27:05 +00:00
let APP = await this.renderToString(context)
if (!context.nuxt.serverRendered) {
APP = '<div id="__nuxt"></div>'
}
const m = context.meta.inject()
let HEAD = m.meta.text() + m.title.text() + m.link.text() + m.style.text() + m.script.text() + m.noscript.text()
2017-05-17 09:27:05 +00:00
if (this._routerBaseSpecified) {
HEAD += `<base href="${this.options.router.base}">`
}
2017-05-21 15:03:21 +00:00
const resourceHints = context.renderResourceHints()
HEAD += resourceHints + context.renderStyles()
2017-06-05 08:57:41 +00:00
APP += `<script type="text/javascript">window.__NUXT__=${serialize(context.nuxt, {isJSON: true})}</script>`
APP += context.renderScripts()
2017-05-17 09:27:05 +00:00
const html = this.appTemplate({
HTML_ATTRS: 'data-n-head-ssr ' + m.htmlAttrs.text(),
BODY_ATTRS: m.bodyAttrs.text(),
HEAD,
APP
2016-11-28 15:44:38 +00:00
})
return {
html,
2017-05-21 15:03:21 +00:00
resourceHints,
error: context.nuxt.error,
redirected: context.redirected
}
2016-11-28 15:44:38 +00:00
}
2016-12-07 18:02:06 +00:00
// Function used to do dom checking via jsdom
2016-12-20 16:56:06 +00:00
let jsdom = null
2017-05-30 14:08:51 +00:00
export async function renderAndGetWindow (url, opts = {}) {
2016-12-20 17:26:46 +00:00
/* istanbul ignore if */
2016-12-20 16:56:06 +00:00
if (!jsdom) {
try {
2017-05-30 14:08:51 +00:00
jsdom = require('jsdom')
2016-12-20 16:56:06 +00:00
} catch (e) {
console.error('Fail when calling nuxt.renderAndGetWindow(url)') // eslint-disable-line no-console
console.error('jsdom module is not installed') // eslint-disable-line no-console
console.error('Please install jsdom with: npm install --save-dev jsdom') // eslint-disable-line no-console
process.exit(1)
}
}
2017-05-30 14:08:51 +00:00
let options = {
resources: 'usable', // load subresources (https://github.com/tmpvar/jsdom#loading-subresources)
runScripts: 'dangerously',
2017-05-30 16:18:01 +00:00
beforeParse (window) {
2017-05-30 14:08:51 +00:00
// Mock window.scrollTo
2017-06-05 08:57:41 +00:00
window.scrollTo = () => {
}
2017-05-30 14:08:51 +00:00
}
}
if (opts.virtualConsole !== false) {
options.virtualConsole = new jsdom.VirtualConsole().sendTo(console)
2017-01-26 14:21:02 +00:00
}
2016-12-07 18:02:06 +00:00
url = url || 'http://localhost:3000'
2017-06-05 08:57:41 +00:00
const {window} = await jsdom.JSDOM.fromURL(url, options)
2017-05-30 14:08:51 +00:00
// If Nuxt could not be loaded (error from the server-side)
2017-05-30 16:18:01 +00:00
const nuxtExists = window.document.body.innerHTML.includes('window.__NUXT__')
if (!nuxtExists) {
2017-06-02 16:09:20 +00:00
/* istanbul ignore next */
2017-05-30 14:08:51 +00:00
let error = new Error('Could not load the nuxt app')
2017-06-02 16:09:20 +00:00
/* istanbul ignore next */
2017-05-30 16:18:01 +00:00
error.body = window.document.body.innerHTML
2017-05-30 14:08:51 +00:00
throw error
}
// Used by nuxt.js to say when the components are loaded and the app ready
await new Promise((resolve) => {
window._onNuxtLoaded = () => resolve(window)
2016-12-07 18:02:06 +00:00
})
2017-05-30 14:08:51 +00:00
// Send back window object
return window
2016-12-07 18:02:06 +00:00
}