Consistent parens in arrow functions (#3630)

* Minor consistency enhancements

* Arrow parenthesis consistency

* Change linting rule

* Fix typo

* Update .eslintrc.js to only require parens for blocks

* Update style according to brace-only suggestion

* Remove --fix from lint

* Tweak no-loading time (failing test)

* Tweak no-loading time (failing test) (2)

* Tweak no-loading time (failing test) (3)

* Tweak no-loading time (failing test) (4)

* Tweak no-loading time (failing test) (5)
This commit is contained in:
Jonas Galvez 2018-08-05 21:12:44 -03:00 committed by Sébastien Chopin
parent 0e42e98751
commit 3f1d634fb7
58 changed files with 226 additions and 170 deletions

View File

@ -38,8 +38,8 @@ module.exports = {
// Allow unresolved imports // Allow unresolved imports
'import/no-unresolved': 0, 'import/no-unresolved': 0,
// Allow paren-less arrow functions // Allow paren-less arrow functions only when there's no braces
'arrow-parens': 0, 'arrow-parens': [2, 'as-needed', { requireForBlockBody: true }],
// Allow async-await // Allow async-await
'generator-star-spacing': 0, 'generator-star-spacing': 0,

View File

@ -16,7 +16,7 @@ const getNuxtConfigFile = argv => resolve(getRootDir(argv), argv['config-file'])
exports.nuxtConfigFile = getNuxtConfigFile exports.nuxtConfigFile = getNuxtConfigFile
exports.loadNuxtConfig = argv => { exports.loadNuxtConfig = (argv) => {
const rootDir = getRootDir(argv) const rootDir = getRootDir(argv)
const nuxtConfigFile = getNuxtConfigFile(argv) const nuxtConfigFile = getNuxtConfigFile(argv)
@ -46,7 +46,7 @@ exports.loadNuxtConfig = argv => {
return options return options
} }
exports.getLatestHost = argv => { exports.getLatestHost = (argv) => {
const port = const port =
argv.port || process.env.PORT || process.env.npm_package_config_nuxt_port argv.port || process.env.PORT || process.env.npm_package_config_nuxt_port
const host = const host =

View File

@ -6,7 +6,7 @@
<script> <script>
// See https://vuejs.org/v2/guide/components.html#Advanced-Async-Components // See https://vuejs.org/v2/guide/components.html#Advanced-Async-Components
const getPost = (slug) => ({ const getPost = slug => ({
component: import(`@/posts/${slug}`), component: import(`@/posts/${slug}`),
error: require('@/posts/404') error: require('@/posts/404')
}) })

View File

@ -6,7 +6,7 @@ export default function () {
test: /\.coffee$/, test: /\.coffee$/,
loader: 'coffee-loader' loader: 'coffee-loader'
} }
this.extendBuild(config => { this.extendBuild((config) => {
// Add CoffeeScruot loader // Add CoffeeScruot loader
config.module.rules.push(coffeeLoader) config.module.rules.push(coffeeLoader)
// Add .coffee extension in webpack resolve // Add .coffee extension in webpack resolve

View File

@ -16,7 +16,7 @@ const components = {
vText: () => import('@/components/text.vue' /* webpackChunkName: "components/text" */), vText: () => import('@/components/text.vue' /* webpackChunkName: "components/text" */),
vImage: () => import('@/components/image.vue' /* webpackChunkName: "components/image" */), vImage: () => import('@/components/image.vue' /* webpackChunkName: "components/image" */),
vCode: () => import('@/components/code.vue' /* webpackChunkName: "components/code" */), vCode: () => import('@/components/code.vue' /* webpackChunkName: "components/code" */),
vChart: () => import('@/components/chart.js' /* webpackChunkName: "components/chart" */).then((m) => m.default()) vChart: () => import('@/components/chart.js' /* webpackChunkName: "components/chart" */).then(m => m.default())
} }
export default { export default {

View File

@ -17,7 +17,7 @@ const components = {
vText: () => import('@/components/text.vue' /* webpackChunkName: "components/text" */), vText: () => import('@/components/text.vue' /* webpackChunkName: "components/text" */),
vImage: () => import('@/components/image.vue' /* webpackChunkName: "components/image" */), vImage: () => import('@/components/image.vue' /* webpackChunkName: "components/image" */),
vCode: () => import('@/components/code.vue' /* webpackChunkName: "components/code" */), vCode: () => import('@/components/code.vue' /* webpackChunkName: "components/code" */),
vChart: () => import('@/components/chart.js' /* webpackChunkName: "components/chart" */).then((m) => m.default()) vChart: () => import('@/components/chart.js' /* webpackChunkName: "components/chart" */).then(m => m.default())
} }
export default { export default {

View File

@ -22,7 +22,7 @@ export default {
// Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.) // Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.)
watchQuery: ['page'], watchQuery: ['page'],
// Key for <nuxt-child> (transitions) // Key for <nuxt-child> (transitions)
key: (to) => to.fullPath, key: to => to.fullPath,
// Called to know which transition to apply // Called to know which transition to apply
transition(to, from) { transition(to, from) {
if (!from) return 'slide-left' if (!from) return 'slide-left'

View File

@ -24,7 +24,7 @@
<script> <script>
import Post from '~/components/post' import Post from '~/components/post'
import vP from '~/components/paragraph' import vP from '~/components/paragraph'
const vHr = { render: (h) => h('hr', { class: 'hr' }) } const vHr = { render: h => h('hr', { class: 'hr' }) }
export default { export default {
components: { components: {

View File

@ -11,7 +11,7 @@ export default {
return !isNaN(+params.id) return !isNaN(+params.id)
}, },
asyncData({ params, env, error }) { asyncData({ params, env, error }) {
const user = env.users.find((user) => String(user.id) === params.id) const user = env.users.find(user => String(user.id) === params.id)
if (!user) { if (!user) {
return error({ message: 'User not found', statusCode: 404 }) return error({ message: 'User not found', statusCode: 404 })
} }

View File

@ -22,7 +22,7 @@ export default {
// Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.) // Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.)
watchQuery: ['page'], watchQuery: ['page'],
// Key for <nuxt-child> (transitions) // Key for <nuxt-child> (transitions)
key: (to) => to.fullPath, key: to => to.fullPath,
// Called to know which transition to apply // Called to know which transition to apply
transition(to, from) { transition(to, from) {
if (!from) return 'slide-left' if (!from) return 'slide-left'

View File

@ -22,7 +22,7 @@ export default {
// Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.) // Watch for $route.query.page to call Component methods (asyncData, fetch, validate, layout, etc.)
watchQuery: ['page'], watchQuery: ['page'],
// Key for <nuxt-child> (transitions) // Key for <nuxt-child> (transitions)
key: (to) => to.fullPath, key: to => to.fullPath,
// Called to know which transition to apply // Called to know which transition to apply
transition(to, from) { transition(to, from) {
if (!from) return 'slide-left' if (!from) return 'slide-left'

View File

@ -103,7 +103,7 @@ storiesOf('Features/Method for rendering Vue', module)
})) }))
storiesOf('Features/Decorator for Vue', module) storiesOf('Features/Decorator for Vue', module)
.addDecorator(story => { .addDecorator((story) => {
// Decorated with story function // Decorated with story function
const WrapButton = story() const WrapButton = story()
return { return {
@ -142,7 +142,7 @@ storiesOf('Features/Addon Actions', module)
.add('Action and method', () => ({ .add('Action and method', () => ({
template: '<my-button :handle-click="log">Click me to log the action</my-button>', template: '<my-button :handle-click="log">Click me to log the action</my-button>',
methods: { methods: {
log: e => { log: (e) => {
e.preventDefault() e.preventDefault()
action('log2')(e.target) action('log2')(e.target)
} }

View File

@ -2,7 +2,7 @@ export default function () {
// Add .ts extension for store, middleware and more // Add .ts extension for store, middleware and more
this.nuxt.options.extensions.push('ts') this.nuxt.options.extensions.push('ts')
// Extend build // Extend build
this.extendBuild(config => { this.extendBuild((config) => {
const tsLoader = { const tsLoader = {
loader: 'ts-loader', loader: 'ts-loader',
options: { options: {

View File

@ -22,7 +22,7 @@ export default {
const res = await axios.get(`https://api.github.com/repos/nuxt/nuxt.js/stats/contributors?access_token=${env.githubToken}`) const res = await axios.get(`https://api.github.com/repos/nuxt/nuxt.js/stats/contributors?access_token=${env.githubToken}`)
return { return {
doughnutChartData: { doughnutChartData: {
labels: res.data.map((stat) => stat.author.login), labels: res.data.map(stat => stat.author.login),
datasets: [ datasets: [
{ {
label: 'Nuxt.js Contributors', label: 'Nuxt.js Contributors',

View File

@ -14,12 +14,12 @@ export default {
const res = await axios.get(`https://api.github.com/repos/nuxt/nuxt.js/stats/commit_activity?access_token=${env.githubToken}`) const res = await axios.get(`https://api.github.com/repos/nuxt/nuxt.js/stats/commit_activity?access_token=${env.githubToken}`)
return { return {
barChartData: { barChartData: {
labels: res.data.map((stat) => moment(stat.week * 1000).format('GGGG[-W]WW')), labels: res.data.map(stat => moment(stat.week * 1000).format('GGGG[-W]WW')),
datasets: [ datasets: [
{ {
label: 'Nuxt.js Commit Activity', label: 'Nuxt.js Commit Activity',
backgroundColor: '#41b883', backgroundColor: '#41b883',
data: res.data.map((stat) => stat.total) data: res.data.map(stat => stat.total)
} }
] ]
} }

View File

@ -5,8 +5,8 @@ export const state = () => ({
}) })
export const mutations = { export const mutations = {
increment: (state) => state.counter++, increment: state => state.counter++,
decrement: (state) => state.counter-- decrement: state => state.counter--
} }
export const plugins = [ export const plugins = [

View File

@ -19,14 +19,14 @@ test.before(async () => {
}, 30000) }, 30000)
// Example of testing only generated html // Example of testing only generated html
test('Route / exits and render HTML', async t => { test('Route / exits and render HTML', async (t) => {
const context = {} const context = {}
const { html } = await nuxt.renderRoute('/', context) const { html } = await nuxt.renderRoute('/', context)
t.true(html.includes('<h1 class="red">Hello world!</h1>')) t.true(html.includes('<h1 class="red">Hello world!</h1>'))
}) })
// Example of testing via dom checking // Example of testing via dom checking
test('Route / exits and render HTML with CSS applied', async t => { test('Route / exits and render HTML with CSS applied', async (t) => {
const context = {} const context = {}
const { html } = await nuxt.renderRoute('/', context) const { html } = await nuxt.renderRoute('/', context)
const { window } = new JSDOM(html).window const { window } = new JSDOM(html).window
@ -38,6 +38,6 @@ test('Route / exits and render HTML with CSS applied', async t => {
}) })
// Close server and ask nuxt to stop listening to file changes // Close server and ask nuxt to stop listening to file changes
test.after('Closing server and nuxt.js', t => { test.after('Closing server and nuxt.js', (t) => {
nuxt.close() nuxt.close()
}) })

View File

@ -6,7 +6,7 @@ const io = socketIO(server)
export default function () { export default function () {
// overwrite nuxt.listen() // overwrite nuxt.listen()
this.nuxt.listen = (port, host) => new Promise((resolve) => server.listen(port || 3000, host || 'localhost', resolve)) this.nuxt.listen = (port, host) => new Promise(resolve => server.listen(port || 3000, host || 'localhost', resolve))
// close this server on 'close' event // close this server on 'close' event
this.nuxt.hook('close', () => new Promise(server.close)) this.nuxt.hook('close', () => new Promise(server.close))

View File

@ -2,7 +2,7 @@ import test from 'tape'
import { shallow } from 'vue-test-utils' import { shallow } from 'vue-test-utils'
import Index from '../pages/index.vue' import Index from '../pages/index.vue'
test('renders Index.vue correctly', t => { test('renders Index.vue correctly', (t) => {
t.plan(4) t.plan(4)
const wrapper = shallow(Index, { const wrapper = shallow(Index, {

View File

@ -4,7 +4,7 @@ import Vue from 'vue'
import '<%= relativeToBuild(resolvePath(c.src || c)) %>' import '<%= relativeToBuild(resolvePath(c.src || c)) %>'
<% }) %> <% }) %>
<%= Object.keys(layouts).map(key => { <%= Object.keys(layouts).map((key) => {
if (splitChunks.layouts) { if (splitChunks.layouts) {
return `const _${hash(key)} = () => import('${layouts[key]}' /* webpackChunkName: "${wChunk('layouts/' + key)}" */).then(m => m.default || m)` return `const _${hash(key)} = () => import('${layouts[key]}' /* webpackChunkName: "${wChunk('layouts/' + key)}" */).then(m => m.default || m)`
} else { } else {
@ -87,8 +87,9 @@ export default {
return this.layout return this.layout
}, },
loadLayout (layout) { loadLayout (layout) {
if (!layout || !(layouts['_' + layout] || resolvedLayouts['_' + layout])) layout = 'default' const undef = !layout
let _layout = '_' + layout const inexisting = !(layouts[`_${layout}`] || resolvedLayouts[`_` + layout])
let _layout = `_${(undef || inexisting) ? 'default' : layout}`
if (resolvedLayouts[_layout]) { if (resolvedLayouts[_layout]) {
return Promise.resolve(resolvedLayouts[_layout]) return Promise.resolve(resolvedLayouts[_layout])
} }
@ -106,13 +107,17 @@ export default {
} }
<% } else { %> <% } else { %>
setLayout(layout) { setLayout(layout) {
if (!layout || !layouts['_' + layout]) layout = 'default' if (!layout || !layouts['_' + layout]) {
layout = 'default'
}
this.layoutName = layout this.layoutName = layout
this.layout = layouts['_' + layout] this.layout = layouts['_' + layout]
return this.layout return this.layout
}, },
loadLayout(layout) { loadLayout(layout) {
if (!layout || !layouts['_' + layout]) layout = 'default' if (!layout || !layouts['_' + layout]) {
layout = 'default'
}
return Promise.resolve(layouts['_' + layout]) return Promise.resolve(layouts['_' + layout])
} }
<% } %> <% } %>

View File

@ -44,12 +44,12 @@ Vue.config.errorHandler = function (err, vm, info) {
if (typeof defaultErrorHandler === 'function') { if (typeof defaultErrorHandler === 'function') {
handled = defaultErrorHandler(...arguments) handled = defaultErrorHandler(...arguments)
} }
if(handled === true){ if (handled === true){
return handled return handled
} }
// Show Nuxt Error Page // Show Nuxt Error Page
if(vm && vm.$root && vm.$root.$nuxt && vm.$root.$nuxt.error && info !== 'render function') { if (vm && vm.$root && vm.$root.$nuxt && vm.$root.$nuxt.error && info !== 'render function') {
vm.$root.$nuxt.error(nuxtError) vm.$root.$nuxt.error(nuxtError)
} }
if (typeof defaultErrorHandler === 'function') { if (typeof defaultErrorHandler === 'function') {
@ -68,7 +68,7 @@ Vue.config.errorHandler = function (err, vm, info) {
// Create and mount App // Create and mount App
createApp() createApp()
.then(mountApp) .then(mountApp)
.catch(err => { .catch((err) => {
if (err.message === 'ERR_REDIRECT') { if (err.message === 'ERR_REDIRECT') {
return // Wait for browser to redirect... return // Wait for browser to redirect...
} }
@ -87,12 +87,12 @@ function componentOption(component, key, ...args) {
} }
function mapTransitions(Components, to, from) { function mapTransitions(Components, to, from) {
const componentTransitions = component => { const componentTransitions = (component) => {
const transition = componentOption(component, 'transition', to, from) || {} const transition = componentOption(component, 'transition', to, from) || {}
return (typeof transition === 'string' ? { name: transition } : transition) return (typeof transition === 'string' ? { name: transition } : transition)
} }
return Components.map(Component => { return Components.map((Component) => {
// Clone original object to prevent overrides // Clone original object to prevent overrides
const transitions = Object.assign({}, componentTransitions(Component)) const transitions = Object.assign({}, componentTransitions(Component))
@ -100,8 +100,8 @@ function mapTransitions(Components, to, from) {
if (from && from.matched.length && from.matched[0].components.default) { if (from && from.matched.length && from.matched[0].components.default) {
const from_transitions = componentTransitions(from.matched[0].components.default) const from_transitions = componentTransitions(from.matched[0].components.default)
Object.keys(from_transitions) Object.keys(from_transitions)
.filter(key => from_transitions[key] && key.toLowerCase().indexOf('leave') !== -1) .filter((key) => from_transitions[key] && key.toLowerCase().indexOf('leave') !== -1)
.forEach(key => { transitions[key] = from_transitions[key] }) .forEach((key) => { transitions[key] = from_transitions[key] })
} }
return transitions return transitions
@ -142,7 +142,7 @@ async function loadAsyncComponents (to, from, next) {
next() next()
} catch (err) { } catch (err) {
err = err || {} err = err || {}
const statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500 const statusCode = (err.statusCode || err.status || (err.response && err.response.status) || 500)
this.error({ statusCode, message: err.message }) this.error({ statusCode, message: err.message })
this.$nuxt.$emit('routeChanged', to, from, err) this.$nuxt.$emit('routeChanged', to, from, err)
next(false) next(false)
@ -183,14 +183,14 @@ function callMiddleware (Components, context, layout) {
if (layout.middleware) { if (layout.middleware) {
midd = midd.concat(layout.middleware) midd = midd.concat(layout.middleware)
} }
Components.forEach(Component => { Components.forEach((Component) => {
if (Component.options.middleware) { if (Component.options.middleware) {
midd = midd.concat(Component.options.middleware) midd = midd.concat(Component.options.middleware)
} }
}) })
} }
midd = midd.map(name => { midd = midd.map((name) => {
if (typeof name === 'function') return name if (typeof name === 'function') return name
if (typeof middleware[name] !== 'function') { if (typeof middleware[name] !== 'function') {
unknownMiddleware = true unknownMiddleware = true
@ -209,14 +209,24 @@ async function render (to, from, next) {
if (to === from) _lastPaths = [] if (to === from) _lastPaths = []
else { else {
const fromMatches = [] const fromMatches = []
_lastPaths = getMatchedComponents(from, fromMatches).map((Component, i) => compile(from.matched[fromMatches[i]].path)(from.params)) _lastPaths = getMatchedComponents(from, fromMatches).map((Component, i) => {
return compile(from.matched[fromMatches[i]].path)(from.params)
})
} }
// nextCalled is true when redirected // nextCalled is true when redirected
let nextCalled = false let nextCalled = false
const _next = path => { const _next = (path) => {
<% if(loading) { %>if (from.path === path.path && this.$loading.finish) this.$loading.finish()<% } %> <% if (loading) { %>
<% if(loading) { %>if (from.path !== path.path && this.$loading.pause) this.$loading.pause()<% } %> if (from.path === path.path && this.$loading.finish) {
this.$loading.finish()
}
<% } %>
<% if (loading) { %>
if (from.path !== path.path && this.$loading.pause) {
this.$loading.pause()
}
<% } %>
if (nextCalled) return if (nextCalled) return
nextCalled = true nextCalled = true
next(path) next(path)
@ -241,7 +251,11 @@ async function render (to, from, next) {
await callMiddleware.call(this, Components, app.context) await callMiddleware.call(this, Components, app.context)
if (nextCalled) return if (nextCalled) return
// Load layout for error page // Load layout for error page
const layout = await this.loadLayout(typeof NuxtError.layout === 'function' ? NuxtError.layout(app.context) : NuxtError.layout) const layout = await this.loadLayout(
typeof NuxtError.layout === 'function'
? NuxtError.layout(app.context)
: NuxtError.layout
)
await callMiddleware.call(this, Components, app.context, layout) await callMiddleware.call(this, Components, app.context, layout)
if (nextCalled) return if (nextCalled) return
// Show error page // Show error page
@ -250,7 +264,7 @@ async function render (to, from, next) {
} }
// Update ._data and other properties if hot reloaded // Update ._data and other properties if hot reloaded
Components.forEach(Component => { Components.forEach((Component) => {
if (Component._Ctor && Component._Ctor.options) { if (Component._Ctor && Component._Ctor.options) {
Component.options.asyncData = Component._Ctor.options.asyncData Component.options.asyncData = Component._Ctor.options.asyncData
Component.options.fetch = Component._Ctor.options.fetch Component.options.fetch = Component._Ctor.options.fetch
@ -280,7 +294,7 @@ async function render (to, from, next) {
// Call .validate() // Call .validate()
let isValid = true let isValid = true
Components.forEach(Component => { Components.forEach((Component) => {
if (!isValid) return if (!isValid) return
if (typeof Component.options.validate !== 'function') return if (typeof Component.options.validate !== 'function') return
isValid = Component.options.validate(app.context) isValid = Component.options.validate(app.context)
@ -314,16 +328,25 @@ async function render (to, from, next) {
let promises = [] let promises = []
const hasAsyncData = Component.options.asyncData && typeof Component.options.asyncData === 'function' const hasAsyncData = (
Component.options.asyncData &&
typeof Component.options.asyncData === 'function'
)
const hasFetch = !!Component.options.fetch const hasFetch = !!Component.options.fetch
<% if (loading) { %>const loadingIncrease = (hasAsyncData && hasFetch) ? 30 : 45<% } %> <% if (loading) { %>
const loadingIncrease = (hasAsyncData && hasFetch) ? 30 : 45
<% } %>
// Call asyncData(context) // Call asyncData(context)
if (hasAsyncData) { if (hasAsyncData) {
const promise = promisify(Component.options.asyncData, app.context) const promise = promisify(Component.options.asyncData, app.context)
.then(asyncDataResult => { .then((asyncDataResult) => {
applyAsyncData(Component, asyncDataResult) applyAsyncData(Component, asyncDataResult)
<% if(loading) { %>if(this.$loading.increase) this.$loading.increase(loadingIncrease)<% } %> <% if (loading) { %>
if(this.$loading.increase) {
this.$loading.increase(loadingIncrease)
}
<% } %>
}) })
promises.push(promise) promises.push(promise)
} }
@ -337,8 +360,12 @@ async function render (to, from, next) {
if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) { if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) {
p = Promise.resolve(p) p = Promise.resolve(p)
} }
p.then(fetchResult => { p.then((fetchResult) => {
<% if(loading) { %>if(this.$loading.increase) this.$loading.increase(loadingIncrease)<% } %> <% if (loading) { %>
if (this.$loading.increase) {
this.$loading.increase(loadingIncrease)
}
<% } %>
}) })
promises.push(p) promises.push(p)
} }
@ -348,17 +375,21 @@ async function render (to, from, next) {
// If not redirected // If not redirected
if (!nextCalled) { if (!nextCalled) {
<% if (loading) { %> <% if (loading) { %>
if (this.$loading.finish && !this.$loading.manual) this.$loading.finish() if (this.$loading.finish) {
this.$loading.finish()
}
<% } %> <% } %>
next() next()
} }
} catch (error) { } catch (error) {
if (!error) error = {} if (!error) {
error = {}
}
_lastPaths = [] _lastPaths = []
error.statusCode = error.statusCode || error.status || (error.response && error.response.status) || 500 const errorResponseStatus = (error.response && error.response.status)
error.statusCode = error.statusCode || error.status || errorResponseStatus || 500
// Load error layout // Load error layout
let layout = NuxtError.layout let layout = NuxtError.layout
@ -393,7 +424,10 @@ function showNextPage(to) {
} }
// Set layout // Set layout
let layout = this.$options.nuxt.err ? NuxtError.layout : to.matched[0].components.default.options.layout let layout = this.$options.nuxt.err
? NuxtError.layout
: to.matched[0].components.default.options.layout
if (typeof layout === 'function') { if (typeof layout === 'function') {
layout = layout(app.context) layout = layout(app.context)
} }
@ -412,8 +446,16 @@ function fixPrepatch(to, ___) {
instances.forEach((instance, i) => { instances.forEach((instance, i) => {
if (!instance) return if (!instance) return
// if (!this._queryChanged && to.matched[matches[i]].path.indexOf(':') === -1 && to.matched[matches[i]].path.indexOf('*') === -1) return // If not a dynamic route, skip // if (
if (instance.constructor._dataRefresh && Components[i] === instance.constructor && typeof instance.constructor.options.data === 'function') { // !this._queryChanged &&
// to.matched[matches[i]].path.indexOf(':') === -1 &&
// to.matched[matches[i]].path.indexOf('*') === -1
// ) return // If not a dynamic route, skip
if (
instance.constructor._dataRefresh &&
Components[i] === instance.constructor &&
typeof instance.constructor.options.data === 'function'
) {
const newData = instance.constructor.options.data.call(instance) const newData = instance.constructor.options.data.call(instance)
for (let key in newData) { for (let key in newData) {
Vue.set(instance.$data, key, newData[key]) Vue.set(instance.$data, key, newData[key])

View File

@ -1,6 +1,16 @@
import Vue from 'vue' import Vue from 'vue'
import NuxtChild from './nuxt-child' import NuxtChild from './nuxt-child'
import NuxtError from '<%= components.ErrorPage ? ((components.ErrorPage.indexOf('~') === 0 || components.ErrorPage.indexOf('@') === 0) ? components.ErrorPage : "../" + components.ErrorPage) : "./nuxt-error.vue" %>'
<% if (components.ErrorPage) { %>
<% if (('~@').includes(components.ErrorPage.charAt(0))) { %>
import NuxtError from '<%= components.ErrorPage %>'
<% } else { %>
import NuxtError from '<%= "../" + components.ErrorPage %>'
<% } %>
<% } else { %>
import NuxtError from './nuxt-error.vue'
<% } %>
import { compile } from '../utils' import { compile } from '../utils'
export default { export default {

View File

@ -12,7 +12,7 @@ import { setContext, getLocation, getRouteData } from './utils'
<% if (store) { %>import { createStore } from './store.js'<% } %> <% if (store) { %>import { createStore } from './store.js'<% } %>
/* Plugins */ /* Plugins */
<% plugins.forEach(plugin => { %>import <%= plugin.name %> from '<%= plugin.name %>' // Source: <%= relativeToBuild(plugin.src) %><%= (plugin.ssr===false) ? ' (ssr: false)' : '' %> <% plugins.forEach((plugin) => { %>import <%= plugin.name %> from '<%= plugin.name %>' // Source: <%= relativeToBuild(plugin.src) %><%= (plugin.ssr===false) ? ' (ssr: false)' : '' %>
<% }) %> <% }) %>
// Component: <no-ssr> // Component: <no-ssr>
@ -156,10 +156,10 @@ async function createApp (ssrContext) {
<% } %> <% } %>
// Plugin execution // Plugin execution
<% plugins.filter(p => p.ssr).forEach(plugin => { %> <% plugins.filter(p => p.ssr).forEach((plugin) => { %>
if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(app.context, inject)<% }) %> if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(app.context, inject)<% }) %>
<% if (plugins.filter(p => !p.ssr).length) { %> <% if (plugins.filter(p => !p.ssr).length) { %>
if (process.browser) { <% plugins.filter(p => !p.ssr).forEach(plugin => { %> if (process.browser) { <% plugins.filter((p) => !p.ssr).forEach((plugin) => { %>
if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(app.context, inject)<% }) %> if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(app.context, inject)<% }) %>
}<% } %> }<% } %>

View File

@ -59,7 +59,7 @@ const scrollBehavior = function (to, from, savedPosition) {
position = savedPosition position = savedPosition
} }
return new Promise(resolve => { return new Promise((resolve) => {
// wait for the out transition to complete (if necessary) // wait for the out transition to complete (if necessary)
window.$nuxt.$once('triggerScroll', () => { window.$nuxt.$once('triggerScroll', () => {
// coords will be used if no selector is provided, // coords will be used if no selector is provided,

View File

@ -12,7 +12,7 @@ const isDev = <%= isDev %>
const noopApp = () => new Vue({ render: (h) => h('div') }) const noopApp = () => new Vue({ render: (h) => h('div') })
const createNext = ssrContext => opts => { const createNext = (ssrContext) => (opts) => {
ssrContext.redirected = opts ssrContext.redirected = opts
// If nuxt generate // If nuxt generate
if (!ssrContext.res) { if (!ssrContext.res) {
@ -40,7 +40,7 @@ const createNext = ssrContext => opts => {
// state of our application before actually rendering it. // state of our application before actually rendering it.
// Since data fetching is async, this function is expected to // Since data fetching is async, this function is expected to
// return a Promise that resolves to the app instance. // return a Promise that resolves to the app instance.
export default async ssrContext => { export default async (ssrContext) => {
// Create ssrContext.next for simulate next() of beforeEach() when wanted to redirect // Create ssrContext.next for simulate next() of beforeEach() when wanted to redirect
ssrContext.redirected = false ssrContext.redirected = false
ssrContext.next = createNext(ssrContext) ssrContext.next = createNext(ssrContext)
@ -170,13 +170,13 @@ export default async ssrContext => {
if (!Components.length) return render404Page() if (!Components.length) return render404Page()
// Call asyncData & fetch hooks on components matched by the route. // Call asyncData & fetch hooks on components matched by the route.
let asyncDatas = await Promise.all(Components.map(Component => { let asyncDatas = await Promise.all(Components.map((Component) => {
let promises = [] let promises = []
// Call asyncData(context) // Call asyncData(context)
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') { if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
let promise = promisify(Component.options.asyncData, app.context) let promise = promisify(Component.options.asyncData, app.context)
promise.then(asyncDataResult => { promise.then((asyncDataResult) => {
ssrContext.asyncData[Component.cid] = asyncDataResult ssrContext.asyncData[Component.cid] = asyncDataResult
applyAsyncData(Component) applyAsyncData(Component)
return asyncDataResult return asyncDataResult

View File

@ -505,7 +505,7 @@ function formatUrl (url, query) {
* @return {string} * @return {string}
*/ */
function formatQuery (query) { function formatQuery (query) {
return Object.keys(query).sort().map(key => { return Object.keys(query).sort().map((key) => {
var val = query[key] var val = query[key]
if (val == null) { if (val == null) {
return '' return ''

View File

@ -63,7 +63,7 @@ export default class Builder {
get plugins() { get plugins() {
return _.uniqBy( return _.uniqBy(
this.options.plugins.map(p => { this.options.plugins.map((p) => {
if (typeof p === 'string') p = { src: p } if (typeof p === 'string') p = { src: p }
const pluginBaseName = path.basename(p.src, path.extname(p.src)).replace( const pluginBaseName = path.basename(p.src, path.extname(p.src)).replace(
/[^a-zA-Z?\d\s:]/g, /[^a-zA-Z?\d\s:]/g,
@ -214,7 +214,7 @@ export default class Builder {
ignore: this.options.ignore ignore: this.options.ignore
}) })
let hasErrorLayout = false let hasErrorLayout = false
layoutsFiles.forEach(file => { layoutsFiles.forEach((file) => {
let name = file let name = file
.split('/') .split('/')
.slice(1) .slice(1)
@ -259,7 +259,7 @@ export default class Builder {
;(await glob(`${this.options.dir.pages}/**/*.{vue,js}`, { ;(await glob(`${this.options.dir.pages}/**/*.{vue,js}`, {
cwd: this.options.srcDir, cwd: this.options.srcDir,
ignore: this.options.ignore ignore: this.options.ignore
})).forEach(f => { })).forEach((f) => {
const key = f.replace(/\.(js|vue)$/, '') const key = f.replace(/\.(js|vue)$/, '')
if (/\.vue$/.test(f) || !files[key]) { if (/\.vue$/.test(f) || !files[key]) {
files[key] = f.replace(/(['|"])/g, '\\$1') files[key] = f.replace(/(['|"])/g, '\\$1')
@ -310,7 +310,7 @@ export default class Builder {
) )
templatesFiles = templatesFiles templatesFiles = templatesFiles
.map(file => { .map((file) => {
// Skip if custom file was already provided in build.templates[] // Skip if custom file was already provided in build.templates[]
if (customTemplateFiles.indexOf(file) !== -1) { if (customTemplateFiles.indexOf(file) !== -1) {
return return
@ -330,7 +330,7 @@ export default class Builder {
// -- Custom templates -- // -- Custom templates --
// Add custom template files // Add custom template files
templatesFiles = templatesFiles.concat( templatesFiles = templatesFiles.concat(
this.options.build.templates.map(t => { this.options.build.templates.map((t) => {
return Object.assign( return Object.assign(
{ {
src: r(this.options.srcDir, t.src || t), src: r(this.options.srcDir, t.src || t),
@ -439,7 +439,7 @@ export default class Builder {
} }
// Alias plugins to their real path // Alias plugins to their real path
this.plugins.forEach(p => { this.plugins.forEach((p) => {
const src = this.relativeToBuild(p.src) const src = this.relativeToBuild(p.src)
// Client config // Client config
@ -455,7 +455,7 @@ export default class Builder {
}) })
// Configure compilers // Configure compilers
this.compilers = compilersOptions.map(compilersOption => { this.compilers = compilersOptions.map((compilersOption) => {
const compiler = webpack(compilersOption) const compiler = webpack(compilersOption)
// In dev, write files in memory FS // In dev, write files in memory FS
@ -476,7 +476,7 @@ export default class Builder {
// Start Builds // Start Builds
const runner = this.options.dev ? parallel : sequence const runner = this.options.dev ? parallel : sequence
await runner(this.compilers, compiler => { await runner(this.compilers, (compiler) => {
return this.webpackCompile(compiler) return this.webpackCompile(compiler)
}) })
} }
@ -488,7 +488,7 @@ export default class Builder {
await this.nuxt.callHook('build:compile', { name, compiler }) await this.nuxt.callHook('build:compile', { name, compiler })
// Load renderer resources after build // Load renderer resources after build
compiler.hooks.done.tap('load-resources', async stats => { compiler.hooks.done.tap('load-resources', async (stats) => {
await this.nuxt.callHook('build:compiled', { await this.nuxt.callHook('build:compiled', {
name, name,
compiler, compiler,
@ -510,7 +510,7 @@ export default class Builder {
} }
// Server, build and watch for changes // Server, build and watch for changes
this.compilersWatching.push( this.compilersWatching.push(
compiler.watch(this.options.watchers.webpack, err => { compiler.watch(this.options.watchers.webpack, (err) => {
/* istanbul ignore if */ /* istanbul ignore if */
if (err) return reject(err) if (err) return reject(err)
}) })

View File

@ -183,7 +183,7 @@ export default class Generator {
'vue-ssr-client-manifest.json' 'vue-ssr-client-manifest.json'
].map(file => path.resolve(this.distNuxtPath, file)) ].map(file => path.resolve(this.distNuxtPath, file))
extraFiles.forEach(file => { extraFiles.forEach((file) => {
if (fsExtra.existsSync(file)) { if (fsExtra.existsSync(file)) {
fsExtra.removeSync(file) fsExtra.removeSync(file)
} }
@ -195,14 +195,11 @@ export default class Generator {
decorateWithPayloads(routes, generateRoutes) { decorateWithPayloads(routes, generateRoutes) {
let routeMap = {} let routeMap = {}
// Fill routeMap for known routes // Fill routeMap for known routes
routes.forEach(route => { routes.forEach((route) => {
routeMap[route] = { routeMap[route] = { route, payload: null }
route,
payload: null
}
}) })
// Fill routeMap with given generate.routes // Fill routeMap with given generate.routes
generateRoutes.forEach(route => { generateRoutes.forEach((route) => {
// route is either a string or like { route : '/my_route/1', payload: {} } // route is either a string or like { route : '/my_route/1', payload: {} }
const path = _.isString(route) ? route : route.route const path = _.isString(route) ? route : route.route
routeMap[path] = { routeMap[path] = {

View File

@ -139,7 +139,7 @@ export default class WebpackBaseConfig {
}, },
{ {
test: /\.jsx?$/, test: /\.jsx?$/,
exclude: file => { exclude: (file) => {
// not exclude files outside node_modules // not exclude files outside node_modules
if (/node_modules/.test(file)) { if (/node_modules/.test(file)) {
for (let module of [/\.vue\.js/].concat(this.options.build.transpile)) { for (let module of [/\.vue\.js/].concat(this.options.build.transpile)) {

View File

@ -5,7 +5,7 @@ export default class StatsPlugin {
} }
apply(compiler) { apply(compiler) {
compiler.hooks.done.tap('stats-plugin', stats => { compiler.hooks.done.tap('stats-plugin', (stats) => {
process.stdout.write( process.stdout.write(
'\n' + '\n' +
stats.toString(this.statsOptions) + stats.toString(this.statsOptions) +

View File

@ -19,10 +19,10 @@ export default class VueSSRClientPlugin {
const initialFiles = uniq(Object.keys(stats.entrypoints) const initialFiles = uniq(Object.keys(stats.entrypoints)
.map(name => stats.entrypoints[name].assets) .map(name => stats.entrypoints[name].assets)
.reduce((assets, all) => all.concat(assets), []) .reduce((assets, all) => all.concat(assets), [])
.filter((file) => isJS(file) || isCSS(file))) .filter(file => isJS(file) || isCSS(file)))
const asyncFiles = allFiles const asyncFiles = allFiles
.filter((file) => isJS(file) || isCSS(file)) .filter(file => isJS(file) || isCSS(file))
.filter(file => initialFiles.indexOf(file) < 0) .filter(file => initialFiles.indexOf(file) < 0)
const manifest = { const manifest = {
@ -35,7 +35,7 @@ export default class VueSSRClientPlugin {
const assetModules = stats.modules.filter(m => m.assets.length) const assetModules = stats.modules.filter(m => m.assets.length)
const fileToIndex = file => manifest.all.indexOf(file) const fileToIndex = file => manifest.all.indexOf(file)
stats.modules.forEach(m => { stats.modules.forEach((m) => {
// ignore modules duplicated in multiple chunks // ignore modules duplicated in multiple chunks
if (m.chunks.length === 1) { if (m.chunks.length === 1) {
const cid = m.chunks[0] const cid = m.chunks[0]
@ -46,7 +46,7 @@ export default class VueSSRClientPlugin {
const id = m.identifier.replace(/\s\w+$/, '') // remove appended hash const id = m.identifier.replace(/\s\w+$/, '') // remove appended hash
const files = manifest.modules[hash(id)] = chunk.files.map(fileToIndex) const files = manifest.modules[hash(id)] = chunk.files.map(fileToIndex)
// find all asset modules associated with the same chunk // find all asset modules associated with the same chunk
assetModules.forEach(m => { assetModules.forEach((m) => {
if (m.chunks.some(id => id === cid)) { if (m.chunks.some(id => id === cid)) {
files.push.apply(files, m.assets.map(fileToIndex)) files.push.apply(files, m.assets.map(fileToIndex))
} }

View File

@ -42,7 +42,7 @@ export default class VueSSRServerPlugin {
maps: {} maps: {}
} }
stats.assets.forEach(asset => { stats.assets.forEach((asset) => {
if (asset.name.match(/\.js$/)) { if (asset.name.match(/\.js$/)) {
bundle.files[asset.name] = compilation.assets[asset.name].source() bundle.files[asset.name] = compilation.assets[asset.name].source()
} else if (asset.name.match(/\.js\.map$/)) { } else if (asset.name.match(/\.js\.map$/)) {

View File

@ -4,7 +4,7 @@ const prefix = `[vue-server-renderer-webpack-plugin]`
export const warn = msg => console.error(chalk.red(`${prefix} ${msg}\n`)) // eslint-disable-line no-console export const warn = msg => console.error(chalk.red(`${prefix} ${msg}\n`)) // eslint-disable-line no-console
export const tip = msg => console.log(chalk.yellow(`${prefix} ${msg}\n`)) // eslint-disable-line no-console export const tip = msg => console.log(chalk.yellow(`${prefix} ${msg}\n`)) // eslint-disable-line no-console
export const validate = compiler => { export const validate = (compiler) => {
if (compiler.options.target !== 'node') { if (compiler.options.target !== 'node') {
warn('webpack config `target` should be "node".') warn('webpack config `target` should be "node".')
} }

View File

@ -1,7 +1,7 @@
export default class WarnFixPlugin { export default class WarnFixPlugin {
apply(compiler) /* istanbul ignore next */ { apply(compiler) /* istanbul ignore next */ {
compiler.hooks.done.tap('warnfix-plugin', stats => { compiler.hooks.done.tap('warnfix-plugin', (stats) => {
stats.compilation.warnings = stats.compilation.warnings.filter(warn => { stats.compilation.warnings = stats.compilation.warnings.filter((warn) => {
if ( if (
warn.name === 'ModuleDependencyWarning' && warn.name === 'ModuleDependencyWarning' &&
warn.message.includes(`export 'default'`) && warn.message.includes(`export 'default'`) &&

View File

@ -60,7 +60,7 @@ export default class WebpackServerConfig extends BaseConfig {
// https://webpack.js.org/configuration/externals/#externals // https://webpack.js.org/configuration/externals/#externals
// https://github.com/liady/webpack-node-externals // https://github.com/liady/webpack-node-externals
// https://vue-loader.vuejs.org/migrating.html#ssr-externals // https://vue-loader.vuejs.org/migrating.html#ssr-externals
this.options.modulesDir.forEach(dir => { this.options.modulesDir.forEach((dir) => {
if (fs.existsSync(dir)) { if (fs.existsSync(dir)) {
config.externals.push( config.externals.push(
nodeExternals({ nodeExternals({

View File

@ -86,7 +86,7 @@ export default class PostcssConfig {
if (isPureObject(plugins)) { if (isPureObject(plugins)) {
// Map postcss plugins into instances on object mode once // Map postcss plugins into instances on object mode once
config.plugins = Object.keys(plugins) config.plugins = Object.keys(plugins)
.map(p => { .map((p) => {
const plugin = require(p) const plugin = require(p)
const opts = plugins[p] const opts = plugins[p]
if (opts === false) return // Disabled if (opts === false) return // Disabled

View File

@ -178,7 +178,7 @@ export const relativeTo = function relativeTo() {
} }
export const flatRoutes = function flatRoutes(router, _path = '', routes = []) { export const flatRoutes = function flatRoutes(router, _path = '', routes = []) {
router.forEach(r => { router.forEach((r) => {
if (!r.path.includes(':') && !r.path.includes('*')) { if (!r.path.includes(':') && !r.path.includes('*')) {
/* istanbul ignore if */ /* istanbul ignore if */
if (r.children) { if (r.children) {
@ -202,7 +202,7 @@ export const flatRoutes = function flatRoutes(router, _path = '', routes = []) {
function cleanChildrenRoutes(routes, isChild = false) { function cleanChildrenRoutes(routes, isChild = false) {
let start = -1 let start = -1
let routesIndex = [] let routesIndex = []
routes.forEach(route => { routes.forEach((route) => {
if (/-index$/.test(route.name) || route.name === 'index') { if (/-index$/.test(route.name) || route.name === 'index') {
// Save indexOf 'index' key in name // Save indexOf 'index' key in name
let res = route.name.split('-') let res = route.name.split('-')
@ -211,7 +211,7 @@ function cleanChildrenRoutes(routes, isChild = false) {
routesIndex.push(res) routesIndex.push(res)
} }
}) })
routes.forEach(route => { routes.forEach((route) => {
route.path = isChild ? route.path.replace('/', '') : route.path route.path = isChild ? route.path.replace('/', '') : route.path
if (route.path.indexOf('?') > -1) { if (route.path.indexOf('?') > -1) {
let names = route.name.split('-') let names = route.name.split('-')
@ -219,7 +219,7 @@ function cleanChildrenRoutes(routes, isChild = false) {
if (!isChild) { if (!isChild) {
paths.shift() paths.shift()
} // clean first / for parents } // clean first / for parents
routesIndex.forEach(r => { routesIndex.forEach((r) => {
let i = r.indexOf('index') - start // children names let i = r.indexOf('index') - start // children names
if (i < paths.length) { if (i < paths.length) {
for (let a = 0; a <= i; a++) { for (let a = 0; a <= i; a++) {
@ -247,7 +247,7 @@ function cleanChildrenRoutes(routes, isChild = false) {
export const createRoutes = function createRoutes(files, srcDir, pagesDir) { export const createRoutes = function createRoutes(files, srcDir, pagesDir) {
let routes = [] let routes = []
files.forEach(file => { files.forEach((file) => {
let keys = file let keys = file
.replace(RegExp(`^${pagesDir}`), '') .replace(RegExp(`^${pagesDir}`), '')
.replace(/\.(vue|js)$/, '') .replace(/\.(vue|js)$/, '')

View File

@ -59,13 +59,11 @@ export default function errorMiddleware(err, req, res, next) {
true true
) )
if (isJson) { if (isJson) {
youch.toJSON().then(json => { youch.toJSON().then((json) => {
sendResponse(JSON.stringify(json, undefined, 2), 'text/json') sendResponse(JSON.stringify(json, undefined, 2), 'text/json')
}) })
} else { } else {
youch.toHTML().then(html => { youch.toHTML().then(html => sendResponse(html))
sendResponse(html)
})
} }
} }

View File

@ -137,7 +137,7 @@ export default class ModuleContainer {
options = {} options = {}
} }
return new Promise(resolve => { return new Promise((resolve) => {
// Call module with `this` context and pass options // Call module with `this` context and pass options
const result = handler.call(this, options) const result = handler.call(this, options)

View File

@ -40,7 +40,7 @@ export default class Nuxt {
// ESM Loader // ESM Loader
this.esm = esm(module, {}) this.esm = esm(module, {})
this._ready = this.ready().catch(err => { this._ready = this.ready().catch((err) => {
consola.fatal(err) consola.fatal(err)
}) })
} }
@ -97,13 +97,10 @@ export default class Nuxt {
} }
addObjectHooks(hooksObj) { addObjectHooks(hooksObj) {
Object.keys(hooksObj).forEach(name => { Object.keys(hooksObj).forEach((name) => {
let hooks = hooksObj[name] let hooks = hooksObj[name]
hooks = Array.isArray(hooks) ? hooks : [hooks] hooks = Array.isArray(hooks) ? hooks : [hooks]
hooks.forEach(hook => this.hook(name, hook))
hooks.forEach(hook => {
this.hook(name, hook)
})
}) })
} }
@ -111,7 +108,6 @@ export default class Nuxt {
if (!this.readyMessage) { if (!this.readyMessage) {
return return
} }
consola.ready({ consola.ready({
message: this.readyMessage, message: this.readyMessage,
badge: true, badge: true,
@ -123,7 +119,7 @@ export default class Nuxt {
return this.ready().then(() => new Promise((resolve, reject) => { return this.ready().then(() => new Promise((resolve, reject) => {
const server = this.renderer.app.listen( const server = this.renderer.app.listen(
{ port, host, exclusive: false }, { port, host, exclusive: false },
err => { (err) => {
/* istanbul ignore if */ /* istanbul ignore if */
if (err) { if (err) {
return reject(err) return reject(err)
@ -143,7 +139,7 @@ export default class Nuxt {
() => () =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
// Destroy server by forcing every connection to be closed // Destroy server by forcing every connection to be closed
server.destroy(err => { server.destroy((err) => {
consola.debug('server closed') consola.debug('server closed')
/* istanbul ignore if */ /* istanbul ignore if */
if (err) { if (err) {

View File

@ -258,7 +258,7 @@ export default class Renderer {
} }
// Add User provided middleware // Add User provided middleware
this.options.serverMiddleware.forEach(m => { this.options.serverMiddleware.forEach((m) => {
this.useMiddleware(m) this.useMiddleware(m)
}) })
@ -420,7 +420,7 @@ export default class Renderer {
window.scrollTo = () => {} window.scrollTo = () => {}
} }
} }
const jsdomErrHandler = err => { throw err } const jsdomErrHandler = (err) => { throw err }
if (opts.virtualConsole !== false) { if (opts.virtualConsole !== false) {
options.virtualConsole = new jsdom.VirtualConsole().sendTo(consola) options.virtualConsole = new jsdom.VirtualConsole().sendTo(consola)
// throw error when window creation failed // throw error when window creation failed
@ -439,7 +439,7 @@ export default class Renderer {
throw error throw error
} }
// Used by nuxt.js to say when the components are loaded and the app ready // Used by nuxt.js to say when the components are loaded and the app ready
await timeout(new Promise(resolve => { await timeout(new Promise((resolve) => {
window._onNuxtLoaded = () => resolve(window) window._onNuxtLoaded = () => resolve(window)
}), 20000, 'Components loading in renderAndGetWindow was not completed in 20s') }), 20000, 'Components loading in renderAndGetWindow was not completed in 20s')
if (opts.virtualConsole !== false) { if (opts.virtualConsole !== false) {

View File

@ -28,17 +28,15 @@ describe('basic browser', () => {
}) })
test('/noloading', async () => { test('/noloading', async () => {
const { hook } = await page.nuxt.navigate('/noloading', true) const { hook } = await page.nuxt.navigate('/noloading')
let loading = await page.nuxt.loadingData() let loading = await page.nuxt.loadingData()
expect(loading.show).toBe(true) expect(loading.show).toBe(true)
await hook await hook
expect(loading.show).toBe(true) expect(loading.show).toBe(true)
await new Promise((resolve) => { await page.waitForFunction(`document.querySelector('p').innerText === 'true'`)
setTimeout(() => resolve(), 1800) expect(await page.$text('p')).toBe('true')
})
loading = await page.nuxt.loadingData() loading = await page.nuxt.loadingData()
expect(loading.percent).toBe(100) expect(loading.show).toBe(true)
}) })
test('/stateless', async () => { test('/stateless', async () => {
@ -54,7 +52,7 @@ describe('basic browser', () => {
await page.nuxt.navigate('/css') await page.nuxt.navigate('/css')
expect(await page.$text('.red')).toBe('This is red') expect(await page.$text('.red')).toBe('This is red')
expect(await page.$eval('.red', red => { expect(await page.$eval('.red', (red) => {
const { color, backgroundColor } = window.getComputedStyle(red) const { color, backgroundColor } = window.getComputedStyle(red)
return { color, backgroundColor } return { color, backgroundColor }
})).toEqual({ })).toEqual({

View File

@ -4,6 +4,7 @@ export default {
generate: { generate: {
routes: [ routes: [
// TODO: generate with {build: false} does not scans pages! // TODO: generate with {build: false} does not scans pages!
'/noloading',
'/stateless', '/stateless',
'/css', '/css',
'/stateful', '/stateful',

View File

@ -4,7 +4,7 @@
<script> <script>
const fetchData = () => { const fetchData = () => {
return new Promise(resolve => { return new Promise((resolve) => {
setTimeout(() => resolve({ name: 'Await Nuxt.js' }), 10) setTimeout(() => resolve({ name: 'Await Nuxt.js' }), 10)
}) })
} }

View File

@ -1,5 +1,8 @@
<template> <template>
<p>{{ name }}</p> <div>
<h1>{{ name }}</h1>
<p>{{ loaded }}</p>
</div>
</template> </template>
<script> <script>
@ -7,16 +10,22 @@ export default {
loading: false, loading: false,
asyncData() { asyncData() {
return new Promise((resolve) => { return new Promise((resolve) => {
setTimeout(() => resolve({ name: 'Nuxt.js' }), 10) setTimeout(() => resolve({
loaded: false,
name: 'Nuxt.js'
}), 10)
}) })
}, },
watch: {
$route(to) {
this.$nuxt.$loading.start()
}
},
mounted() { mounted() {
setTimeout(() => this.$nuxt.$loading.finish(), 1500) setTimeout(() => {
this.$nuxt.$loading.finish()
setTimeout(() => {
// Re-enable loader as we move on
// to normal pages in the test
this.$nuxt.$loading.start()
this.loaded = true
}, 1500)
}, 1500)
} }
} }
</script> </script>

View File

@ -18,7 +18,7 @@ async function search(q) {
q = String(q || '').toLowerCase() q = String(q || '').toLowerCase()
return new Promise((resolve) => { return new Promise((resolve) => {
const searchResults = countries.filter((s) => s.toLowerCase().includes(q)) const searchResults = countries.filter(s => s.toLowerCase().includes(q))
setTimeout(() => resolve(searchResults), 100) setTimeout(() => resolve(searchResults), 100)
}) })
} }

View File

@ -2,26 +2,26 @@ export default function () {
let ctr = 1 let ctr = 1
// Add hook for module // Add hook for module
this.nuxt.hook('modules:done', moduleContainer => { this.nuxt.hook('modules:done', (moduleContainer) => {
this.nuxt.__module_hook = moduleContainer && ctr++ this.nuxt.__module_hook = moduleContainer && ctr++
}) })
// Add hook for renderer // Add hook for renderer
this.nuxt.hook('render:done', renderer => { this.nuxt.hook('render:done', (renderer) => {
this.nuxt.__renderer_hook = renderer && ctr++ this.nuxt.__renderer_hook = renderer && ctr++
}) })
// Get data before data sent to client // Get data before data sent to client
this.nuxt.hook('render:context', data => { this.nuxt.hook('render:context', (data) => {
this.nuxt.__render_context = data this.nuxt.__render_context = data
}) })
// Add hook for build // Add hook for build
this.nuxt.hook('build:done', builder => { this.nuxt.hook('build:done', (builder) => {
this.nuxt.__builder_hook = builder && ctr++ this.nuxt.__builder_hook = builder && ctr++
}) })
this.nuxt.hook('build:done', builder => { this.nuxt.hook('build:done', (builder) => {
this.nuxt.__builder_plugin = builder && ctr++ this.nuxt.__builder_plugin = builder && ctr++
}) })
} }

View File

@ -13,14 +13,14 @@ export default {
], ],
serverMiddleware: ['./modules/middleware/midd2'], serverMiddleware: ['./modules/middleware/midd2'],
hooks(hook) { hooks(hook) {
hook('ready', nuxt => { hook('ready', (nuxt) => {
nuxt.__ready_called__ = true nuxt.__ready_called__ = true
}) })
hook('build:done', builder => { hook('build:done', (builder) => {
builder.__build_done__ = true builder.__build_done__ = true
}) })
// Add hook for renderer // Add hook for renderer
hook('render:before', renderer => { hook('render:before', (renderer) => {
renderer.useMiddleware({ renderer.useMiddleware({
path: '/use-middleware', path: '/use-middleware',
handler: '~/modules/middleware/use-middleware' handler: '~/modules/middleware/use-middleware'

View File

@ -5,7 +5,7 @@
</template> </template>
<script> <script>
const AsyncTest = () => import('@/components/test.vue').then((m) => m.default || m) const AsyncTest = () => import('@/components/test.vue').then(m => m.default || m)
export default { export default {
components: { components: {

View File

@ -21,7 +21,7 @@ describe('basic dev', () => {
extend({ module: { rules } }, { isClient }) { extend({ module: { rules } }, { isClient }) {
if (isClient) { if (isClient) {
const babelLoader = rules.find(loader => loader.test.test('.jsx')) const babelLoader = rules.find(loader => loader.test.test('.jsx'))
transpile = (file) => !babelLoader.exclude(file) transpile = file => !babelLoader.exclude(file)
} }
} }
} }

View File

@ -13,7 +13,7 @@ describe('basic fail generate', () => {
const nuxt = new Nuxt(options) const nuxt = new Nuxt(options)
const generator = new Generator(nuxt) const generator = new Generator(nuxt)
await generator.generate({ build: false }).catch(e => { await generator.generate({ build: false }).catch((e) => {
expect(e.message).toBe('Not today!') expect(e.message).toBe('Not today!')
}) })
}) })

View File

@ -20,15 +20,15 @@ describe.skip.appveyor('cli', () => {
const nuxtStart = spawn('node', [nuxtBin, 'start', rootDir], { env }) const nuxtStart = spawn('node', [nuxtBin, 'start', rootDir], { env })
nuxtStart.stdout.on('data', data => { nuxtStart.stdout.on('data', (data) => {
stdout += data stdout += data
}) })
nuxtStart.on('error', err => { nuxtStart.on('error', (err) => {
error = err error = err
}) })
nuxtStart.on('close', code => { nuxtStart.on('close', (code) => {
exitCode = code exitCode = code
}) })

View File

@ -20,15 +20,15 @@ describe.skip.appveyor('cli', () => {
const nuxtStart = spawn('node', [nuxtBin, 'start', rootDir], { env }) const nuxtStart = spawn('node', [nuxtBin, 'start', rootDir], { env })
nuxtStart.stdout.on('data', data => { nuxtStart.stdout.on('data', (data) => {
stdout += data stdout += data
}) })
nuxtStart.on('error', err => { nuxtStart.on('error', (err) => {
error = err error = err
}) })
nuxtStart.on('close', code => { nuxtStart.on('close', (code) => {
exitCode = code exitCode = code
}) })

View File

@ -9,7 +9,7 @@ describe('dynamic routes', () => {
return readFile( return readFile(
resolve(__dirname, '..', 'fixtures/dynamic-routes/.nuxt/router.js'), resolve(__dirname, '..', 'fixtures/dynamic-routes/.nuxt/router.js'),
'utf-8' 'utf-8'
).then(routerFile => { ).then((routerFile) => {
routerFile = routerFile routerFile = routerFile
.slice(routerFile.indexOf('routes: [')) .slice(routerFile.indexOf('routes: ['))
.replace('routes: [', '[') .replace('routes: [', '[')

View File

@ -25,7 +25,7 @@ describe('nuxt', () => {
rootDir: resolve(__dirname, '..', 'fixtures', 'empty', 'pages') rootDir: resolve(__dirname, '..', 'fixtures', 'empty', 'pages')
}) })
return new Builder(nuxt).build().catch(err => { return new Builder(nuxt).build().catch((err) => {
let s = String(err) let s = String(err)
expect(s.includes('No `pages` directory found')).toBe(true) expect(s.includes('No `pages` directory found')).toBe(true)
expect(s.includes('Did you mean to run `nuxt` in the parent (`../`) directory?')).toBe(true) expect(s.includes('Did you mean to run `nuxt` in the parent (`../`) directory?')).toBe(true)

View File

@ -7,7 +7,7 @@ let nuxt = null
let port let port
const url = route => 'http://localhost:' + port + route const url = route => 'http://localhost:' + port + route
const renderRoute = async _url => { const renderRoute = async (_url) => {
const window = await nuxt.renderAndGetWindow(url(_url)) const window = await nuxt.renderAndGetWindow(url(_url))
const head = window.document.head.innerHTML const head = window.document.head.innerHTML
const html = window.document.body.innerHTML const html = window.document.body.innerHTML

View File

@ -61,7 +61,7 @@ describe('utils', () => {
const array = [1] const array = [1]
const promise = Utils.promisifyRoute(array) const promise = Utils.promisifyRoute(array)
expect(typeof promise).toBe('object') expect(typeof promise).toBe('object')
return promise.then(res => { return promise.then((res) => {
expect(res).toBe(array) expect(res).toBe(array)
}) })
}) })
@ -73,7 +73,7 @@ describe('utils', () => {
} }
const promise = Utils.promisifyRoute(fn) const promise = Utils.promisifyRoute(fn)
expect(typeof promise).toBe('object') expect(typeof promise).toBe('object')
return promise.then(res => { return promise.then((res) => {
expect(res).toBe(array) expect(res).toBe(array)
}) })
}) })
@ -81,27 +81,27 @@ describe('utils', () => {
test('promisifyRoute (fn => promise)', () => { test('promisifyRoute (fn => promise)', () => {
const array = [1, 2, 3] const array = [1, 2, 3]
const fn = function () { const fn = function () {
return new Promise(resolve => { return new Promise((resolve) => {
resolve(array) resolve(array)
}) })
} }
const promise = Utils.promisifyRoute(fn) const promise = Utils.promisifyRoute(fn)
expect(typeof promise).toBe('object') expect(typeof promise).toBe('object')
return promise.then(res => { return promise.then((res) => {
expect(res).toBe(array) expect(res).toBe(array)
}) })
}) })
test('promisifyRoute ((fn(args) => promise))', () => { test('promisifyRoute ((fn(args) => promise))', () => {
const fn = function (array) { const fn = function (array) {
return new Promise(resolve => { return new Promise((resolve) => {
resolve(array) resolve(array)
}) })
} }
const array = [1, 2, 3] const array = [1, 2, 3]
const promise = Utils.promisifyRoute(fn, array) const promise = Utils.promisifyRoute(fn, array)
expect(typeof promise).toBe('object') expect(typeof promise).toBe('object')
return promise.then(res => { return promise.then((res) => {
expect(res).toBe(array) expect(res).toBe(array)
}) })
}) })
@ -112,7 +112,7 @@ describe('utils', () => {
} }
const promise = Utils.promisifyRoute(fn) const promise = Utils.promisifyRoute(fn)
expect(typeof promise).toBe('object') expect(typeof promise).toBe('object')
return promise.catch(e => { return promise.catch((e) => {
expect(e.message).toBe('Error here') expect(e.message).toBe('Error here')
}) })
}) })
@ -124,7 +124,7 @@ describe('utils', () => {
const array = [1, 2, 3, 4] const array = [1, 2, 3, 4]
const promise = Utils.promisifyRoute(fn, array) const promise = Utils.promisifyRoute(fn, array)
expect(typeof promise).toBe('object') expect(typeof promise).toBe('object')
return promise.catch(e => { return promise.catch((e) => {
expect(e.message).toBe('Error here: ' + array.join()) expect(e.message).toBe('Error here: ' + array.join())
}) })
}) })
@ -136,7 +136,7 @@ describe('utils', () => {
} }
const promise = Utils.promisifyRoute(fn) const promise = Utils.promisifyRoute(fn)
expect(typeof promise).toBe('object') expect(typeof promise).toBe('object')
return promise.then(res => { return promise.then((res) => {
expect(res).toBe(array) expect(res).toBe(array)
}) })
}) })
@ -149,7 +149,7 @@ describe('utils', () => {
const object = { a: 1 } const object = { a: 1 }
const promise = Utils.promisifyRoute(fn, array, object) const promise = Utils.promisifyRoute(fn, array, object)
expect(typeof promise).toBe('object') expect(typeof promise).toBe('object')
return promise.then(res => { return promise.then((res) => {
expect(res.array).toBe(array) expect(res.array).toBe(array)
expect(res.object).toBe(object) expect(res.object).toBe(object)
}) })

View File

@ -55,7 +55,7 @@ export default class Browser {
return { hook } return { hook }
}, },
routeData() { routeData() {
return page.evaluate($nuxt => { return page.evaluate(($nuxt) => {
return { return {
path: $nuxt.$route.path, path: $nuxt.$route.path,
query: $nuxt.$route.query query: $nuxt.$route.query