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
'import/no-unresolved': 0,
// Allow paren-less arrow functions
'arrow-parens': 0,
// Allow paren-less arrow functions only when there's no braces
'arrow-parens': [2, 'as-needed', { requireForBlockBody: true }],
// Allow async-await
'generator-star-spacing': 0,

View File

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

View File

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

View File

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

View File

@ -16,7 +16,7 @@ const components = {
vText: () => import('@/components/text.vue' /* webpackChunkName: "components/text" */),
vImage: () => import('@/components/image.vue' /* webpackChunkName: "components/image" */),
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 {

View File

@ -17,7 +17,7 @@ const components = {
vText: () => import('@/components/text.vue' /* webpackChunkName: "components/text" */),
vImage: () => import('@/components/image.vue' /* webpackChunkName: "components/image" */),
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 {

View File

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

View File

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

View File

@ -11,7 +11,7 @@ export default {
return !isNaN(+params.id)
},
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) {
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.)
watchQuery: ['page'],
// Key for <nuxt-child> (transitions)
key: (to) => to.fullPath,
key: to => to.fullPath,
// Called to know which transition to apply
transition(to, from) {
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.)
watchQuery: ['page'],
// Key for <nuxt-child> (transitions)
key: (to) => to.fullPath,
key: to => to.fullPath,
// Called to know which transition to apply
transition(to, from) {
if (!from) return 'slide-left'

View File

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

View File

@ -2,7 +2,7 @@ export default function () {
// Add .ts extension for store, middleware and more
this.nuxt.options.extensions.push('ts')
// Extend build
this.extendBuild(config => {
this.extendBuild((config) => {
const tsLoader = {
loader: 'ts-loader',
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}`)
return {
doughnutChartData: {
labels: res.data.map((stat) => stat.author.login),
labels: res.data.map(stat => stat.author.login),
datasets: [
{
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}`)
return {
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: [
{
label: 'Nuxt.js Commit Activity',
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 = {
increment: (state) => state.counter++,
decrement: (state) => state.counter--
increment: state => state.counter++,
decrement: state => state.counter--
}
export const plugins = [

View File

@ -19,14 +19,14 @@ test.before(async () => {
}, 30000)
// 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 { html } = await nuxt.renderRoute('/', context)
t.true(html.includes('<h1 class="red">Hello world!</h1>'))
})
// 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 { html } = await nuxt.renderRoute('/', context)
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
test.after('Closing server and nuxt.js', t => {
test.after('Closing server and nuxt.js', (t) => {
nuxt.close()
})

View File

@ -6,7 +6,7 @@ const io = socketIO(server)
export default function () {
// 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
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 Index from '../pages/index.vue'
test('renders Index.vue correctly', t => {
test('renders Index.vue correctly', (t) => {
t.plan(4)
const wrapper = shallow(Index, {

View File

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

View File

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

View File

@ -1,6 +1,16 @@
import Vue from 'vue'
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'
export default {

View File

@ -12,7 +12,7 @@ import { setContext, getLocation, getRouteData } from './utils'
<% if (store) { %>import { createStore } from './store.js'<% } %>
/* 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>
@ -156,10 +156,10 @@ async function createApp (ssrContext) {
<% } %>
// 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 (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)<% }) %>
}<% } %>

View File

@ -59,7 +59,7 @@ const scrollBehavior = function (to, from, savedPosition) {
position = savedPosition
}
return new Promise(resolve => {
return new Promise((resolve) => {
// wait for the out transition to complete (if necessary)
window.$nuxt.$once('triggerScroll', () => {
// 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 createNext = ssrContext => opts => {
const createNext = (ssrContext) => (opts) => {
ssrContext.redirected = opts
// If nuxt generate
if (!ssrContext.res) {
@ -40,7 +40,7 @@ const createNext = ssrContext => opts => {
// state of our application before actually rendering it.
// Since data fetching is async, this function is expected to
// 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
ssrContext.redirected = false
ssrContext.next = createNext(ssrContext)
@ -170,13 +170,13 @@ export default async ssrContext => {
if (!Components.length) return render404Page()
// 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 = []
// Call asyncData(context)
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
let promise = promisify(Component.options.asyncData, app.context)
promise.then(asyncDataResult => {
promise.then((asyncDataResult) => {
ssrContext.asyncData[Component.cid] = asyncDataResult
applyAsyncData(Component)
return asyncDataResult

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -42,7 +42,7 @@ export default class VueSSRServerPlugin {
maps: {}
}
stats.assets.forEach(asset => {
stats.assets.forEach((asset) => {
if (asset.name.match(/\.js$/)) {
bundle.files[asset.name] = compilation.assets[asset.name].source()
} 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 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') {
warn('webpack config `target` should be "node".')
}

View File

@ -1,7 +1,7 @@
export default class WarnFixPlugin {
apply(compiler) /* istanbul ignore next */ {
compiler.hooks.done.tap('warnfix-plugin', stats => {
stats.compilation.warnings = stats.compilation.warnings.filter(warn => {
compiler.hooks.done.tap('warnfix-plugin', (stats) => {
stats.compilation.warnings = stats.compilation.warnings.filter((warn) => {
if (
warn.name === 'ModuleDependencyWarning' &&
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://github.com/liady/webpack-node-externals
// https://vue-loader.vuejs.org/migrating.html#ssr-externals
this.options.modulesDir.forEach(dir => {
this.options.modulesDir.forEach((dir) => {
if (fs.existsSync(dir)) {
config.externals.push(
nodeExternals({

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -258,7 +258,7 @@ export default class Renderer {
}
// Add User provided middleware
this.options.serverMiddleware.forEach(m => {
this.options.serverMiddleware.forEach((m) => {
this.useMiddleware(m)
})
@ -420,7 +420,7 @@ export default class Renderer {
window.scrollTo = () => {}
}
}
const jsdomErrHandler = err => { throw err }
const jsdomErrHandler = (err) => { throw err }
if (opts.virtualConsole !== false) {
options.virtualConsole = new jsdom.VirtualConsole().sendTo(consola)
// throw error when window creation failed
@ -439,7 +439,7 @@ export default class Renderer {
throw error
}
// 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)
}), 20000, 'Components loading in renderAndGetWindow was not completed in 20s')
if (opts.virtualConsole !== false) {

View File

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

View File

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

View File

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

View File

@ -1,5 +1,8 @@
<template>
<p>{{ name }}</p>
<div>
<h1>{{ name }}</h1>
<p>{{ loaded }}</p>
</div>
</template>
<script>
@ -7,16 +10,22 @@ export default {
loading: false,
asyncData() {
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() {
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>

View File

@ -18,7 +18,7 @@ async function search(q) {
q = String(q || '').toLowerCase()
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)
})
}

View File

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

View File

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

View File

@ -5,7 +5,7 @@
</template>
<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 {
components: {

View File

@ -21,7 +21,7 @@ describe('basic dev', () => {
extend({ module: { rules } }, { isClient }) {
if (isClient) {
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 generator = new Generator(nuxt)
await generator.generate({ build: false }).catch(e => {
await generator.generate({ build: false }).catch((e) => {
expect(e.message).toBe('Not today!')
})
})

View File

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

View File

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

View File

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

View File

@ -25,7 +25,7 @@ describe('nuxt', () => {
rootDir: resolve(__dirname, '..', 'fixtures', 'empty', 'pages')
})
return new Builder(nuxt).build().catch(err => {
return new Builder(nuxt).build().catch((err) => {
let s = String(err)
expect(s.includes('No `pages` directory found')).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
const url = route => 'http://localhost:' + port + route
const renderRoute = async _url => {
const renderRoute = async (_url) => {
const window = await nuxt.renderAndGetWindow(url(_url))
const head = window.document.head.innerHTML
const html = window.document.body.innerHTML

View File

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

View File

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