Merge branch 'master' into pr/44

# Conflicts:
#	lib/build/index.js
This commit is contained in:
Sébastien Chopin 2016-12-08 21:13:20 +01:00
commit b73675206a
12 changed files with 71 additions and 55 deletions

View File

@ -21,7 +21,9 @@ module.exports = {
// allow async-await // allow async-await
'generator-star-spacing': 0, 'generator-star-spacing': 0,
// allow debugger during development // allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
// do not allow console.logs etc...
'no-console': 2
}, },
globals: {} globals: {}
} }

View File

@ -84,12 +84,13 @@ const options = {
} }
// Launch nuxt build with given options // Launch nuxt build with given options
new Nuxt(options) let nuxt = new Nuxt(options)
.then((nuxt) => { nuxt.build()
.then(() => {
// You can use nuxt.render(req, res) or nuxt.renderRoute(route, context) // You can use nuxt.render(req, res) or nuxt.renderRoute(route, context)
}) })
.catch((error) { .catch((e) => {
// If an error appended while building the project // An error appended during the build
}) })
``` ```

View File

@ -19,13 +19,13 @@ if (typeof options.rootDir !== 'string') {
} }
options.dev = false // Create production build when calling `nuxt build` options.dev = false // Create production build when calling `nuxt build`
console.log('[nuxt] Building...') console.log('[nuxt] Building...') // eslint-disable-line no-console
const nuxt = new Nuxt(options) const nuxt = new Nuxt(options)
nuxt.build() nuxt.build()
.then(() => { .then(() => {
console.log('[nuxt] Building done') console.log('[nuxt] Building done') // eslint-disable-line no-console
}) })
.catch((err) => { .catch((err) => {
console.error(err) console.error(err) // eslint-disable-line no-console
process.exit(1) process.exit(1)
}) })

View File

@ -19,13 +19,13 @@ if (typeof options.rootDir !== 'string') {
} }
options.dev = false // Force production mode (no webpack middlewares called) options.dev = false // Force production mode (no webpack middlewares called)
console.log('[nuxt] Generating...') console.log('[nuxt] Generating...') // eslint-disable-line no-console
const nuxt = new Nuxt(options) const nuxt = new Nuxt(options)
nuxt.generate() nuxt.generate()
.then(() => { .then(() => {
console.log('[nuxt] Generate done') console.log('[nuxt] Generate done') // eslint-disable-line no-console
}) })
.catch((err) => { .catch((err) => {
console.error(err) console.error(err) // eslint-disable-line no-console
process.exit() process.exit()
}) })

View File

@ -0,0 +1,11 @@
module.exports = {
head: {
title: 'Auth Routes',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', content: 'Auth Routes example' }
]
},
loading: { color: '#3B8070' }
}

View File

@ -31,15 +31,17 @@ app.post('/api/logout', function (req, res) {
// We instantiate Nuxt.js with the options // We instantiate Nuxt.js with the options
const isProd = process.env.NODE_ENV === 'production' const isProd = process.env.NODE_ENV === 'production'
const nuxt = new Nuxt({ dev: !isProd }) let config = require('./nuxt.config.js')
config.dev = !isProd
const nuxt = new Nuxt(config)
// No build in production // No build in production
const promise = (isProd ? Promise.resolve() : nuxt.build()) const promise = (isProd ? Promise.resolve() : nuxt.build())
promise.then(() => { promise.then(() => {
app.use(nuxt.render) app.use(nuxt.render)
app.listen(3000) app.listen(3000)
console.log('Server is listening on http://localhost:3000') console.log('Server is listening on http://localhost:3000') // eslint-disable-line no-console
}) })
.catch((error) => { .catch((error) => {
console.error(error) console.error(error) // eslint-disable-line no-console
process.exit(1) process.exit(1)
}) })

View File

@ -282,5 +282,5 @@ Promise.all(resolveComponents)
}) })
}) })
.catch((err) => { .catch((err) => {
console.error('[nuxt.js] Cannot load components', err) console.error('[nuxt.js] Cannot load components', err) // eslint-disable-line no-console
}) })

View File

@ -88,15 +88,14 @@ exports.options = function () {
} }
exports.build = function * () { exports.build = function * () {
console.log(this.srcDir)
/* /*
** Check if pages dir exists and warn if not ** Check if pages dir exists and warn if not
*/ */
if (!fs.existsSync(join(this.srcDir, 'pages'))) { if (!fs.existsSync(join(this.srcDir, 'pages'))) {
if (fs.existsSync(join(this.srcDir, '..', 'pages'))) { if (fs.existsSync(join(this.srcDir, '..', 'pages'))) {
console.error('> No `pages` directory found. Did you mean to run `nuxt` in the parent (`../`) directory?') console.error('> No `pages` directory found. Did you mean to run `nuxt` in the parent (`../`) directory?') // eslint-disable-line no-console
} else { } else {
console.error('> Couldn\'t find a `pages` directory. Please create one under the project root') console.error('> Couldn\'t find a `pages` directory. Please create one under the project root') // eslint-disable-line no-console
} }
process.exit(1) process.exit(1)
} }
@ -209,7 +208,7 @@ function * generateRoutesAndFiles () {
templateVars.components.ErrorPage = r(this.srcDir, 'pages/_error.vue') templateVars.components.ErrorPage = r(this.srcDir, 'pages/_error.vue')
} }
if (fs.existsSync(join(this.srcDir, 'layouts', 'error.vue'))) { if (fs.existsSync(join(this.srcDir, 'layouts', 'error.vue'))) {
templateVars.appPath = r(this.srcDir, 'layouts/error.vue') templateVars.components.ErrorPage = r(this.dir, 'layouts/error.vue')
} }
let moveTemplates = templatesFiles.map((file) => { let moveTemplates = templatesFiles.map((file) => {
return readFile(r(__dirname, '..', 'app', file), 'utf8') return readFile(r(__dirname, '..', 'app', file), 'utf8')
@ -264,8 +263,8 @@ function webpackWatchAndUpdate () {
this.webpackServerWatcher = serverCompiler.watch({}, (err, stats) => { this.webpackServerWatcher = serverCompiler.watch({}, (err, stats) => {
if (err) throw err if (err) throw err
stats = stats.toJson() stats = stats.toJson()
stats.errors.forEach(err => console.error(err)) stats.errors.forEach(err => console.error(err)) // eslint-disable-line no-console
stats.warnings.forEach(err => console.warn(err)) stats.warnings.forEach(err => console.warn(err)) // eslint-disable-line no-console
createRenderer.call(this, mfs.readFileSync(outputPath, 'utf-8')) createRenderer.call(this, mfs.readFileSync(outputPath, 'utf-8'))
}) })
} }
@ -276,7 +275,7 @@ function webpackRunClient () {
const serverCompiler = webpack(clientConfig) const serverCompiler = webpack(clientConfig)
serverCompiler.run((err, stats) => { serverCompiler.run((err, stats) => {
if (err) return reject(err) if (err) return reject(err)
console.log('[nuxt:build:client]\n', stats.toString({ chunks: false, colors: true })) console.log('[nuxt:build:client]\n', stats.toString({ chunks: false, colors: true })) // eslint-disable-line no-console
resolve() resolve()
}) })
}) })
@ -288,7 +287,7 @@ function webpackRunServer () {
const serverCompiler = webpack(serverConfig) const serverCompiler = webpack(serverConfig)
serverCompiler.run((err, stats) => { serverCompiler.run((err, stats) => {
if (err) return reject(err) if (err) return reject(err)
console.log('[nuxt:build:server]\n', stats.toString({ chunks: false, colors: true })) console.log('[nuxt:build:server]\n', stats.toString({ chunks: false, colors: true })) // eslint-disable-line no-console
const bundlePath = join(serverConfig.output.path, serverConfig.output.filename) const bundlePath = join(serverConfig.output.path, serverConfig.output.filename)
readFile(bundlePath, 'utf8') readFile(bundlePath, 'utf8')
.then((bundle) => { .then((bundle) => {
@ -326,7 +325,7 @@ function watchPages () {
var d = Date.now() var d = Date.now()
co(generateRoutesAndFiles.bind(this)) co(generateRoutesAndFiles.bind(this))
.then(() => { .then(() => {
console.log('Time to gen:' + (Date.now() - d) + 'ms') console.log('Time to gen:' + (Date.now() - d) + 'ms') // eslint-disable-line no-console
}) })
}, 200) }, 200)
this.pagesFilesWatcher = chokidar.watch(patterns, options) this.pagesFilesWatcher = chokidar.watch(patterns, options)

View File

@ -7,7 +7,7 @@ const pify = require('pify')
const pathToRegexp = require('path-to-regexp') const pathToRegexp = require('path-to-regexp')
const _ = require('lodash') const _ = require('lodash')
const { resolve, join, dirname, sep } = require('path') const { resolve, join, dirname, sep } = require('path')
const { urlJoin, promisifyRouteParams } = require('./utils') const { promisifyRouteParams } = require('./utils')
const copy = pify(fs.copy) const copy = pify(fs.copy)
const remove = pify(fs.remove) const remove = pify(fs.remove)
const writeFile = pify(fs.writeFile) const writeFile = pify(fs.writeFile)
@ -19,15 +19,16 @@ const defaults = {
} }
module.exports = function () { module.exports = function () {
const s = Date.now()
/* /*
** Update loaders config to add router.base path ** Update loaders config to add router.base path
*/ */
this.options.build.loaders.forEach((config) => { // this.options.build.loaders.forEach((config) => {
if (['file', 'url', 'file-loader', 'url-loader'].includes(config.loader)) { // if (['file', 'url', 'file-loader', 'url-loader'].includes(config.loader)) {
config.query = config.query || {} // config.query = config.query || {}
config.query.publicPath = urlJoin(this.options.router.base, '/_nuxt/') // config.query.publicPath = urlJoin(this.options.router.base, '/_nuxt/')
} // }
}) // })
/* /*
** Set variables ** Set variables
*/ */
@ -66,40 +67,38 @@ module.exports = function () {
/* /*
** Generate html files from routes ** Generate html files from routes
*/ */
var promises = [] let routes = []
this.routes.forEach((route) => { this.routes.forEach((route) => {
let subRoutes = []
if (route.path.includes(':') || route.path.includes('*')) { if (route.path.includes(':') || route.path.includes('*')) {
const routeParams = this.options.generate.routeParams[route.path] const routeParams = this.options.generate.routeParams[route.path]
if (!routeParams) { if (!routeParams) {
console.error(`Could not generate the dynamic route ${route.path}, please add the mapping params in nuxt.config.js (generate.routeParams).`) console.error(`Could not generate the dynamic route ${route.path}, please add the mapping params in nuxt.config.js (generate.routeParams).`) // eslint-disable-line no-console
return process.exit(1) return process.exit(1)
} }
const toPath = pathToRegexp.compile(route.path) const toPath = pathToRegexp.compile(route.path)
routeParams.forEach((params) => { routes = routes.concat(routeParams.map((params) => {
const newRoute = Object.assign({}, route, { path: toPath(params) }) return Object.assign({}, route, { path: toPath(params) })
subRoutes.push(newRoute) }))
})
} else { } else {
subRoutes.push(route) routes.push(route)
} }
subRoutes.forEach((route) => { })
var promise = this.renderRoute(route.path) return co(function * () {
.then(({ html }) => { while (routes.length) {
yield routes.splice(0, 500).map((route) => {
return co(function * () {
const { html } = yield self.renderRoute(route.path)
var path = join(route.path, sep, 'index.html') // /about -> /about/index.html var path = join(route.path, sep, 'index.html') // /about -> /about/index.html
debug('Generate file: ' + path) debug('Generate file: ' + path)
path = join(distPath, path) path = join(distPath, path)
// Make sure the sub folders are created // Make sure the sub folders are created
return co(function * () {
yield mkdirp(dirname(path)) yield mkdirp(dirname(path))
yield writeFile(path, html, 'utf8') yield writeFile(path, html, 'utf8')
}) })
}) })
promises.push(promise) }
}) })
}) })
return Promise.all(promises)
})
.then((pages) => { .then((pages) => {
// Add .nojekyll file to let Github Pages add the _nuxt/ folder // Add .nojekyll file to let Github Pages add the _nuxt/ folder
// https://help.github.com/articles/files-that-start-with-an-underscore-are-missing/ // https://help.github.com/articles/files-that-start-with-an-underscore-are-missing/
@ -107,7 +106,9 @@ module.exports = function () {
return writeFile(nojekyllPath, '') return writeFile(nojekyllPath, '')
}) })
.then(() => { .then(() => {
debug('HTML Files generated') const duration = Math.round((Date.now() - s) / 100) / 10
debug(`HTML Files generated in ${duration}s`)
return this
}) })
} }
@ -119,8 +120,8 @@ function resolveRouteParams (routeParams) {
routeParams[routePath] = routeParamsData routeParams[routePath] = routeParamsData
}) })
.catch((e) => { .catch((e) => {
console.error(`Could not resolve routeParams[${routePath}]`) console.error(`Could not resolve routeParams[${routePath}]`) // eslint-disable-line no-console
console.error(e) console.error(e) // eslint-disable-line no-console
process.exit(1) process.exit(1)
}) })
promises.push(promise) promises.push(promise)

View File

@ -5,7 +5,7 @@ const { getContext } = require('./utils')
exports.render = function (req, res) { exports.render = function (req, res) {
if (!this.renderer && !this.dev) { if (!this.renderer && !this.dev) {
console.error('> No build files found, please run `nuxt build` before launching `nuxt start`') console.error('> No build files found, please run `nuxt build` before launching `nuxt start`') // eslint-disable-line no-console
process.exit(1) process.exit(1)
} }
if (!this.renderer) { if (!this.renderer) {

View File

@ -19,7 +19,7 @@ class Server {
host = host || 'localhost' host = host || 'localhost'
port = port || 3000 port = port || 3000
this.server.listen(port, host, () => { this.server.listen(port, host, () => {
console.log('Ready on http://%s:%s', host, port) console.log('Ready on http://%s:%s', host, port) // eslint-disable-line no-console
}) })
return this return this
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "nuxt", "name": "nuxt",
"version": "0.8.2", "version": "0.8.3",
"description": "A minimalistic framework for server-rendered Vue.js applications (inspired by Next.js)", "description": "A minimalistic framework for server-rendered Vue.js applications (inspired by Next.js)",
"contributors": [ "contributors": [
{ {