chore: lint vue-app templates (#6390)

This commit is contained in:
Pim 2019-09-10 11:51:14 +02:00 committed by Pooya Parsa
parent 8ccca220ed
commit 8f0f16b076
20 changed files with 329 additions and 226 deletions

View File

@ -36,7 +36,7 @@ module.exports = {
'vue/component-name-in-template-casing': ['warn', 'kebab-case'] 'vue/component-name-in-template-casing': ['warn', 'kebab-case']
} }
}, { }, {
files: [ 'test/fixtures/*/.nuxt*/**/+(App|index|server|client).js' ], files: [ 'test/fixtures/*/.nuxt*/**/+(App|index|server|client|nuxt).js' ],
rules: { rules: {
'import/order': 'off' 'import/order': 'off'
} }

View File

@ -41,7 +41,7 @@
"consola": "^2.10.1", "consola": "^2.10.1",
"cross-spawn": "^7.0.0", "cross-spawn": "^7.0.0",
"eslint": "^6.3.0", "eslint": "^6.3.0",
"eslint-multiplexer": "^1.0.4", "eslint-multiplexer": "^2.0.0",
"esm": "^3.2.25", "esm": "^3.2.25",
"execa": "^2.0.4", "execa": "^2.0.4",
"express": "^4.17.1", "express": "^4.17.1",

View File

@ -28,9 +28,9 @@ const layouts = { <%= Object.keys(layouts).map(key => `"_${key}": _${hash(key)}`
export default { export default {
<% if (features.meta) { %> <% if (features.meta) { %>
<%= isTest ? '/* eslint-disable quotes, semi, indent, comma-spacing, key-spacing, object-curly-spacing, space-before-function-paren */' : '' %> <%= isTest ? '/* eslint-disable quotes, semi, indent, comma-spacing, key-spacing, object-curly-spacing, space-before-function-paren, object-shorthand */' : '' %>
head: <%= serializeFunction(head) %>, head: <%= serializeFunction(head) %>,
<%= isTest ? '/* eslint-enable quotes, semi, indent, comma-spacing, key-spacing, object-curly-spacing, space-before-function-paren */' : '' %> <%= isTest ? '/* eslint-enable quotes, semi, indent, comma-spacing, key-spacing, object-curly-spacing, space-before-function-paren, object-shorthand */' : '' %>
<% } %> <% } %>
render (h, props) { render (h, props) {
<% if (loading) { %>const loadingEl = h('NuxtLoading', { ref: 'loading' })<% } %> <% if (loading) { %>const loadingEl = h('NuxtLoading', { ref: 'loading' })<% } %>
@ -121,6 +121,7 @@ export default {
}, },
<% } %> <% } %>
methods: { methods: {
<%= isTest ? '/* eslint-disable comma-dangle */' : '' %>
<% if (features.clientOnline) { %> <% if (features.clientOnline) { %>
refreshOnlineStatus () { refreshOnlineStatus () {
if (process.client) { if (process.client) {
@ -144,7 +145,7 @@ export default {
} }
<% if (loading) { %>this.$loading.start()<% } %> <% if (loading) { %>this.$loading.start()<% } %>
const promises = pages.map(async (page) => { const promises = pages.map((page) => {
const p = [] const p = []
<% if (features.fetch) { %> <% if (features.fetch) { %>
@ -179,8 +180,12 @@ export default {
<% if (loading) { %> <% if (loading) { %>
errorChanged () { errorChanged () {
if (this.nuxt.err && this.$loading) { if (this.nuxt.err && this.$loading) {
if (this.$loading.fail) this.$loading.fail() if (this.$loading.fail) {
if (this.$loading.finish) this.$loading.finish() this.$loading.fail()
}
if (this.$loading.finish) {
this.$loading.finish()
}
} }
}, },
<% } %> <% } %>
@ -188,9 +193,13 @@ export default {
<% if (splitChunks.layouts) { %> <% if (splitChunks.layouts) { %>
setLayout (layout) { setLayout (layout) {
<% if (debug) { %> <% if (debug) { %>
if(layout && typeof layout !== 'string') throw new Error('[nuxt] Avoid using non-string value as layout property.') if(layout && typeof layout !== 'string') {
throw new Error('[nuxt] Avoid using non-string value as layout property.')
}
<% } %> <% } %>
if (!layout || !resolvedLayouts['_' + layout]) layout = 'default' if (!layout || !resolvedLayouts['_' + layout]) {
layout = 'default'
}
this.layoutName = layout this.layoutName = layout
let _layout = '_' + layout let _layout = '_' + layout
this.layout = resolvedLayouts[_layout] this.layout = resolvedLayouts[_layout]
@ -218,7 +227,9 @@ export default {
<% } else { %> <% } else { %>
setLayout (layout) { setLayout (layout) {
<% if (debug) { %> <% if (debug) { %>
if(layout && typeof layout !== 'string') throw new Error('[nuxt] Avoid using non-string value as layout property.') if(layout && typeof layout !== 'string') {
throw new Error('[nuxt] Avoid using non-string value as layout property.')
}
<% } %> <% } %>
if (!layout || !layouts['_' + layout]) { if (!layout || !layouts['_' + layout]) {
layout = 'default' layout = 'default'
@ -241,4 +252,5 @@ export default {
NuxtLoading NuxtLoading
} }
<% } %> <% } %>
<%= isTest ? '/* eslint-enable comma-dangle */' : '' %>
} }

View File

@ -2,21 +2,21 @@ import Vue from 'vue'
<% if (fetch.client) { %>import fetch from 'unfetch'<% } %> <% if (fetch.client) { %>import fetch from 'unfetch'<% } %>
<% if (features.middleware) { %>import middleware from './middleware.js'<% } %> <% if (features.middleware) { %>import middleware from './middleware.js'<% } %>
import { import {
<% if (features.asyncData) { %>applyAsyncData,<% } %> <% if (features.asyncData) { %>applyAsyncData,
promisify,<% } %>
<% if (features.middleware) { %>middlewareSeries,<% } %> <% if (features.middleware) { %>middlewareSeries,<% } %>
sanitizeComponent, <% if (features.transitions || (features.middleware && features.layouts)) { %>sanitizeComponent,<% } %>
resolveRouteComponents, <% if (loading) { %>resolveRouteComponents,<% } %>
getMatchedComponents, getMatchedComponents,
getMatchedComponentsInstances, getMatchedComponentsInstances,
flatMapComponents, flatMapComponents,
setContext, setContext,
promisify, <% if (features.transitions) { %>getLocation,<% } %>
getLocation,
compile, compile,
getQueryDiff, getQueryDiff,
globalHandleError globalHandleError
} from './utils.js' } from './utils.js'
import { createApp, NuxtError } from './index.js' import { createApp<% if (features.layouts) { %>, NuxtError<% } %> } from './index.js'
import NuxtLink from './components/nuxt-link.<%= features.clientPrefetch && router.prefetchLinks ? "client" : "server" %>.js' // should be included after ./index.js import NuxtLink from './components/nuxt-link.<%= features.clientPrefetch && router.prefetchLinks ? "client" : "server" %>.js' // should be included after ./index.js
<% if (isDev) { %>import consola from 'consola'<% } %> <% if (isDev) { %>import consola from 'consola'<% } %>
@ -31,7 +31,7 @@ Vue.component(NuxtLink.name, NuxtLink)
<% if (fetch.client) { %>if (!global.fetch) { global.fetch = fetch }<% } %> <% if (fetch.client) { %>if (!global.fetch) { global.fetch = fetch }<% } %>
// Global shared references // Global shared references
let _lastPaths = [] let _lastPaths = []<%= isTest ? '// eslint-disable-line no-unused-vars' : '' %>
let app let app
let router let router
<% if (store) { %>let store<%= isTest ? '// eslint-disable-line no-unused-vars' : '' %><% } %> <% if (store) { %>let store<%= isTest ? '// eslint-disable-line no-unused-vars' : '' %><% } %>
@ -128,7 +128,7 @@ function mapTransitions(Components, to, from) {
}) })
} }
<% } %> <% } %>
async function loadAsyncComponents(to, from, next) { <% if (loading) { %>async <% } %>function loadAsyncComponents (to, from, next) {
// Check if route path changed (this._pathChanged), only if the page is not an error (for validate()) // Check if route path changed (this._pathChanged), only if the page is not an error (for validate())
this._pathChanged = Boolean(app.nuxt.err) || from.path !== to.path this._pathChanged = Boolean(app.nuxt.err) || from.path !== to.path
this._queryChanged = JSON.stringify(to.query) !== JSON.stringify(from.query) this._queryChanged = JSON.stringify(to.query) !== JSON.stringify(from.query)
@ -141,20 +141,22 @@ async function loadAsyncComponents(to, from, next) {
<% } %> <% } %>
try { try {
<% if (loading) { %>
if (!this._pathChanged && this._queryChanged) {
const Components = await resolveRouteComponents( const Components = await resolveRouteComponents(
to, to,
(Component, instance) => ({ Component, instance }) (Component, instance) => ({ Component, instance })
) )
<% if (loading) { %>
if (!this._pathChanged && this._queryChanged) {
// Add a marker on each component that it needs to refresh or not // Add a marker on each component that it needs to refresh or not
const startLoader = Components.some(({ Component, instance }) => { const startLoader = Components.some(({ Component, instance }) => {
const watchQuery = Component.options.watchQuery const watchQuery = Component.options.watchQuery
if (watchQuery === true) { if (watchQuery === true) {
return true return true
} else if (Array.isArray(watchQuery)) { }
if (Array.isArray(watchQuery)) {
return watchQuery.some(key => this._diffQuery[key]) return watchQuery.some(key => this._diffQuery[key])
} else if (typeof watchQuery === 'function') { }
if (typeof watchQuery === 'function') {
return watchQuery.apply(instance, [to.query, from.query]) return watchQuery.apply(instance, [to.query, from.query])
} }
return false return false
@ -184,6 +186,7 @@ async function loadAsyncComponents(to, from, next) {
} }
} }
<% if (features.transitions) { %>
function applySSRData (Component, ssrData) { function applySSRData (Component, ssrData) {
<% if (features.asyncData) { %> <% if (features.asyncData) { %>
if (NUXT.serverRendered && ssrData) { if (NUXT.serverRendered && ssrData) {
@ -209,6 +212,8 @@ function resolveComponents(router) {
return _Component return _Component
}) })
} }
<% } %>
<% if (features.middleware) { %> <% if (features.middleware) { %>
function callMiddleware (Components, context, layout) { function callMiddleware (Components, context, layout) {
let midd = <%= devalue(router.middleware) %><%= isTest ? '// eslint-disable-line' : '' %> let midd = <%= devalue(router.middleware) %><%= isTest ? '// eslint-disable-line' : '' %>
@ -231,7 +236,9 @@ function callMiddleware(Components, context, layout) {
<% } %> <% } %>
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
this.error({ statusCode: 500, message: 'Unknown middleware ' + name }) this.error({ statusCode: 500, message: 'Unknown middleware ' + name })
@ -239,7 +246,9 @@ function callMiddleware(Components, context, layout) {
return middleware[name] return middleware[name]
}) })
if (unknownMiddleware) return if (unknownMiddleware) {
return
}
return middlewareSeries(midd, context) return middlewareSeries(midd, context)
} }
<% } else if (isDev) { <% } else if (isDev) {
@ -251,10 +260,13 @@ function callMiddleware() {
} }
<% } %> <% } %>
async function render (to, from, next) { async function render (to, from, next) {
if (this._pathChanged === false && this._queryChanged === false) return next() if (this._pathChanged === false && this._queryChanged === false) {
return next()
}
// Handle first render on SPA mode // Handle first render on SPA mode
if (to === from) _lastPaths = [] if (to === from) {
else { _lastPaths = []
} else {
const fromMatches = [] const fromMatches = []
_lastPaths = getMatchedComponents(from, fromMatches).map((Component, i) => { _lastPaths = getMatchedComponents(from, fromMatches).map((Component, i) => {
return compile(from.matched[fromMatches[i]].path)(from.params) return compile(from.matched[fromMatches[i]].path)(from.params)
@ -274,7 +286,10 @@ async function render(to, from, next) {
this.$loading.pause() this.$loading.pause()
} }
<% } %> <% } %>
if (nextCalled) return if (nextCalled) {
return
}
nextCalled = true nextCalled = true
next(path) next(path)
} }
@ -297,7 +312,9 @@ async function render(to, from, next) {
<% if (features.middleware) { %> <% if (features.middleware) { %>
// Default layout // Default layout
await callMiddleware.call(this, Components, app.context) await callMiddleware.call(this, Components, app.context)
if (nextCalled) return if (nextCalled) {
return
}
<% } %> <% } %>
<% if (features.layouts) { %> <% if (features.layouts) { %>
@ -311,7 +328,9 @@ async function render(to, from, next) {
<% if (features.middleware) { %> <% if (features.middleware) { %>
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
@ -337,8 +356,12 @@ async function render(to, from, next) {
<% if (features.middleware) { %> <% if (features.middleware) { %>
// Call middleware // Call middleware
await callMiddleware.call(this, Components, app.context) await callMiddleware.call(this, Components, app.context)
if (nextCalled) return if (nextCalled) {
if (app.context._errored) return next() return
}
if (app.context._errored) {
return next()
}
<% } %> <% } %>
<% if (features.layouts) { %> <% if (features.layouts) { %>
@ -353,8 +376,12 @@ async function render(to, from, next) {
<% if (features.middleware) { %> <% if (features.middleware) { %>
// Call middleware for layout // Call middleware for layout
await callMiddleware.call(this, Components, app.context, layout) await callMiddleware.call(this, Components, app.context, layout)
if (nextCalled) return if (nextCalled) {
if (app.context._errored) return next() return
}
if (app.context._errored) {
return next()
}
<% } %> <% } %>
@ -548,14 +575,18 @@ function showNextPage(to) {
// When navigating on a different route but the same component is used, Vue.js // When navigating on a different route but the same component is used, Vue.js
// Will not update the instance data, so we have to update $data ourselves // Will not update the instance data, so we have to update $data ourselves
function fixPrepatch (to, ___) { function fixPrepatch (to, ___) {
if (this._pathChanged === false && this._queryChanged === false) return if (this._pathChanged === false && this._queryChanged === false) {
return
}
const instances = getMatchedComponentsInstances(to) const instances = getMatchedComponentsInstances(to)
const Components = getMatchedComponents(to) const Components = getMatchedComponents(to)
Vue.nextTick(() => { Vue.nextTick(() => {
instances.forEach((instance, i) => { instances.forEach((instance, i) => {
if (!instance || instance._isDestroyed) return if (!instance || instance._isDestroyed) {
return
}
if ( if (
instance.constructor._dataRefresh && instance.constructor._dataRefresh &&
@ -721,15 +752,12 @@ function addHotReload($component, depth) {
} }
<% } %> <% } %>
async function mountApp(__app) { <% if (features.layouts || features.transitions) { %>async <% } %>function mountApp (__app) {
// Set global variables // Set global variables
app = __app.app app = __app.app
router = __app.router router = __app.router
<% if (store) { %>store = __app.store<% } %> <% if (store) { %>store = __app.store<% } %>
// Resolve route components
const Components = await Promise.all(resolveComponents(router))
// Create Vue instance // Create Vue instance
const _app = new Vue(app) const _app = new Vue(app)
@ -759,6 +787,9 @@ async function mountApp(__app) {
}) })
} }
<% if (features.transitions) { %> <% if (features.transitions) { %>
// Resolve route components
const Components = await Promise.all(resolveComponents(router))
// Enable transitions // Enable transitions
_app.setTransitions = _app.$options.nuxt.setTransitions.bind(_app) _app.setTransitions = _app.$options.nuxt.setTransitions.bind(_app)
if (Components.length) { if (Components.length) {
@ -768,7 +799,9 @@ async function mountApp(__app) {
<% } %> <% } %>
// Initialize error handler // Initialize error handler
_app.$loading = {} // To avoid error while _app.$nuxt does not exist _app.$loading = {} // To avoid error while _app.$nuxt does not exist
if (NUXT.error) _app.error(NUXT.error) if (NUXT.error) {
_app.error(NUXT.error)
}
// Add beforeEach router hooks // Add beforeEach router hooks
router.beforeEach(loadAsyncComponents.bind(_app)) router.beforeEach(loadAsyncComponents.bind(_app))
@ -804,7 +837,9 @@ async function mountApp(__app) {
// Push the path and let route to be resolved // Push the path and let route to be resolved
router.push(path, undefined, (err) => { router.push(path, undefined, (err) => {
if (err) errorHandler(err) if (err) {
errorHandler(err)
}
}) })
}) })
} }

View File

@ -1,6 +1,6 @@
<template> <template>
<transition appear> <transition appear>
<div class="nuxt__build_indicator" :style="indicatorStyle" v-if="building"> <div v-if="building" class="nuxt__build_indicator" :style="indicatorStyle">
<svg viewBox="0 0 96 72" version="1" xmlns="http://www.w3.org/2000/svg"> <svg viewBox="0 0 96 72" version="1" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd"> <g fill="none" fill-rule="evenodd">
<path d="M6 66h23l1-3 21-37L40 6 6 66zM79 66h11L62 17l-5 9 22 37v3zM54 31L35 66h38z" /> <path d="M6 66h23l1-3 21-37L40 6 6 66zM79 66h11L62 17l-5 9 22 37v3zM54 31L35 66h38z" />
@ -16,25 +16,15 @@
<script> <script>
export default { export default {
name: 'nuxt-build-indicator', name: 'NuxtBuildIndicator',
data () { data () {
return { return {
building: false, building: false,
progress: 0, progress: 0,
animatedProgress: 0, animatedProgress: 0,
reconnectAttempts: 0, reconnectAttempts: 0
} }
}, },
mounted() {
if (typeof EventSource === undefined) {
return // Unsupported
}
this.sseConnect()
},
beforeDestroy() {
this.sseClose()
clearInterval(this._progressAnimation)
},
computed: { computed: {
options: () => (<%= JSON.stringify(buildIndicator) %>), options: () => (<%= JSON.stringify(buildIndicator) %>),
indicatorStyle () { indicatorStyle () {
@ -43,7 +33,7 @@ export default {
[d1]: '20px', [d1]: '20px',
[d2]: '20px', [d2]: '20px',
'background-color': this.options.backgroundColor, 'background-color': this.options.backgroundColor,
color: this.options.color, color: this.options.color
} }
} }
}, },
@ -71,6 +61,16 @@ export default {
}, 50) }, 50)
} }
}, },
mounted () {
if (EventSource === undefined) {
return // Unsupported
}
this.sseConnect()
},
beforeDestroy () {
this.sseClose()
clearInterval(this._progressAnimation)
},
methods: { methods: {
sseConnect () { sseConnect () {
if (this._connecting) { if (this._connecting) {
@ -78,11 +78,13 @@ export default {
} }
this._connecting = true this._connecting = true
this.sse = new EventSource('<%= router.base %>_loading/sse') this.sse = new EventSource('<%= router.base %>_loading/sse')
this.sse.addEventListener('message', (event) => this.onSseMessage(event)) this.sse.addEventListener('message', event => this.onSseMessage(event))
}, },
onSseMessage (message) { onSseMessage (message) {
const data = JSON.parse(message.data) const data = JSON.parse(message.data)
if (!data.states) return if (!data.states) {
return
}
this.progress = Math.round(data.states.reduce((p, s) => p + s.progress, 0) / data.states.length) this.progress = Math.round(data.states.reduce((p, s) => p + s.progress, 0) / data.states.length)

View File

@ -6,9 +6,7 @@ const requestIdleCallback = window.requestIdleCallback ||
return setTimeout(function () { return setTimeout(function () {
cb({ cb({
didTimeout: false, didTimeout: false,
timeRemaining: function () { timeRemaining: () => Math.max(0, 50 - (Date.now() - start))
return Math.max(0, 50 - (Date.now() - start))
}
}) })
}, 1) }, 1)
} }

View File

@ -27,6 +27,7 @@ Vue.component(NoSsr.name, {
render (h, ctx) { render (h, ctx) {
if (process.client && !NoSsr._warned) { if (process.client && !NoSsr._warned) {
NoSsr._warned = true NoSsr._warned = true
<%= isTest ? '// eslint-disable-next-line no-console' : '' %>
console.warn(`<no-ssr> has been deprecated and will be removed in Nuxt 3, please use <client-only> instead`) console.warn(`<no-ssr> has been deprecated and will be removed in Nuxt 3, please use <client-only> instead`)
} }
return NoSsr.render(h, ctx) return NoSsr.render(h, ctx)
@ -115,7 +116,9 @@ async function createApp(ssrContext) {
nuxt.dateErr = Date.now() nuxt.dateErr = Date.now()
nuxt.err = err nuxt.err = err
// Used in src/server.js // Used in src/server.js
if (ssrContext) ssrContext.nuxt.error = err if (ssrContext) {
ssrContext.nuxt.error = err
}
return err return err
} }
}, },
@ -150,8 +153,13 @@ async function createApp(ssrContext) {
<% if (plugins.length) { %> <% if (plugins.length) { %>
const inject = function (key, value) { const inject = function (key, value) {
if (!key) throw new Error('inject(key, value) has no key provided') if (!key) {
if (typeof value === 'undefined') throw new Error('inject(key, value) has no value provided') throw new Error('inject(key, value) has no key provided')
}
if (value === undefined) {
throw new Error('inject(key, value) has no value provided')
}
key = '$' + key key = '$' + key
// Add into app // Add into app
app[key] = value app[key] = value
@ -161,7 +169,9 @@ async function createApp(ssrContext) {
<% } %> <% } %>
// Check if plugin not already installed // Check if plugin not already installed
const installKey = '__<%= globals.pluginPrefix %>_' + key + '_installed__' const installKey = '__<%= globals.pluginPrefix %>_' + key + '_installed__'
if (Vue[installKey]) return if (Vue[installKey]) {
return
}
Vue[installKey] = true Vue[installKey] = true
// Call Vue.use() to install the plugin into vm // Call Vue.use() to install the plugin into vm
Vue.use(() => { Vue.use(() => {

View File

@ -1,11 +1,12 @@
const middleware = {} const middleware = {}
<%= isTest ? '/* eslint-disable dot-notation */' : '' %>
<% for (const m of middleware) { <% for (const m of middleware) {
// TODO: remove duplicate logic in v3 (see builder.resolveMiddleware) // TODO: remove duplicate logic in v3 (see builder.resolveMiddleware)
const name = m.name || m.src.replace(new RegExp(`\\.(${extensions})$`), '') const name = m.name || m.src.replace(new RegExp(`\\.(${extensions})$`), '')
const dst = m.dst || relativeToBuild(srcDir, dir.middleware, m.src) const dst = m.dst || relativeToBuild(srcDir, dir.middleware, m.src)
%> %>
middleware['<%= name %>'] = require('<%= dst %>'); middleware['<%= name %>'] = require('<%= dst %>')
middleware['<%= name %>'] = middleware['<%= name %>'].default || middleware['<%= name %>'] middleware['<%= name %>'] = middleware['<%= name %>'].default || middleware['<%= name %>']
<% } %> <% } %>
<%= isTest ? '/* eslint-enable dot-notation */' : '' %>
export default middleware export default middleware

View File

@ -68,7 +68,7 @@ import scrollBehavior from './router.scrollBehavior.js'
return res return res
} }
const _components = [] const _components = []
const _routes = recursiveRoutes(router.routes, ' ', _components, 2) const _routes = recursiveRoutes(router.routes, ' ', _components, 1)
%><%= uniqBy(_components, '_name').map((route) => { %><%= uniqBy(_components, '_name').map((route) => {
if (!route.component) return '' if (!route.component) return ''
const path = relativeToBuild(route.component) const path = relativeToBuild(route.component)

View File

@ -1,5 +1,7 @@
<% if (router.scrollBehavior) { %> <% if (router.scrollBehavior) { %>
<%= isTest ? '/* eslint-disable quotes, semi, indent, comma-spacing, key-spacing, object-curly-spacing, space-before-function-paren */' : '' %>
export default <%= serializeFunction(router.scrollBehavior) %> export default <%= serializeFunction(router.scrollBehavior) %>
<%= isTest ? '/* eslint-enable quotes, semi, indent, comma-spacing, key-spacing, object-curly-spacing, space-before-function-paren */' : '' %>
<% } else { %>import { getMatchedComponents } from './utils' <% } else { %>import { getMatchedComponents } from './utils'
if (process.client) { if (process.client) {
@ -67,6 +69,7 @@ export default function (to, from, savedPosition) {
position = { selector: hash } position = { selector: hash }
} }
} catch (e) { } catch (e) {
<%= isTest ? '// eslint-disable-next-line no-console' : '' %>
console.warn('Failed to save scroll position. Please add CSS.escape() polyfill (https://github.com/mathiasbynens/CSS.escape).') console.warn('Failed to save scroll position. Please add CSS.escape() polyfill (https://github.com/mathiasbynens/CSS.escape).')
} }
} }

View File

@ -5,11 +5,11 @@ import Vue from 'vue'
import { import {
<% if (features.asyncData) { %>applyAsyncData,<% } %> <% if (features.asyncData) { %>applyAsyncData,<% } %>
<% if (features.middleware) { %>middlewareSeries,<% } %> <% if (features.middleware) { %>middlewareSeries,<% } %>
<% if (features.middleware && features.layouts) { %>sanitizeComponent,<% } %>
getMatchedComponents, getMatchedComponents,
promisify, promisify
sanitizeComponent
} from './utils.js' } from './utils.js'
import { createApp, NuxtError } from './index.js' import { createApp<% if (features.layouts) { %>, NuxtError<% } %> } from './index.js'
import NuxtLink from './components/nuxt-link.server.js' // should be included after ./index.js import NuxtLink from './components/nuxt-link.server.js' // should be included after ./index.js
// Component: <NuxtLink> // Component: <NuxtLink>
@ -114,13 +114,17 @@ export default async (ssrContext) => {
try { try {
await store.dispatch('nuxtServerInit', app.context) await store.dispatch('nuxtServerInit', app.context)
} catch (err) { } catch (err) {
console.debug('Error occurred when calling nuxtServerInit: ', err.message) console.debug('Error occurred when calling nuxtServerInit: ', err.message)<%= isTest ? '// eslint-disable-line no-console' : '' %>
throw err throw err
} }
} }
// ...If there is a redirect or an error, stop the process // ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp() if (ssrContext.redirected) {
if (ssrContext.nuxt.error) return renderErrorPage() return noopApp()
}
if (ssrContext.nuxt.error) {
return renderErrorPage()
}
<% } %> <% } %>
<% if (features.middleware) { %> <% if (features.middleware) { %>
@ -129,7 +133,9 @@ export default async (ssrContext) => {
*/ */
let midd = <%= serialize(router.middleware).replace('middleware(', 'function(') %><%= isTest ? '// eslint-disable-line' : '' %> let midd = <%= serialize(router.middleware).replace('middleware(', 'function(') %><%= isTest ? '// eslint-disable-line' : '' %>
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') {
app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name }) app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
} }
@ -137,8 +143,12 @@ export default async (ssrContext) => {
}) })
await middlewareSeries(midd, app.context) await middlewareSeries(midd, app.context)
// ...If there is a redirect or an error, stop the process // ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp() if (ssrContext.redirected) {
if (ssrContext.nuxt.error) return renderErrorPage() return noopApp()
}
if (ssrContext.nuxt.error) {
return renderErrorPage()
}
<% } %> <% } %>
<% if (features.layouts) { %> <% if (features.layouts) { %>
@ -146,9 +156,13 @@ export default async (ssrContext) => {
** Set layout ** Set layout
*/ */
let layout = Components.length ? Components[0].options.layout : NuxtError.layout let layout = Components.length ? Components[0].options.layout : NuxtError.layout
if (typeof layout === 'function') layout = layout(app.context) if (typeof layout === 'function') {
layout = layout(app.context)
}
await _app.loadLayout(layout) await _app.loadLayout(layout)
if (ssrContext.nuxt.error) return renderErrorPage() if (ssrContext.nuxt.error) {
return renderErrorPage()
}
layout = _app.setLayout(layout) layout = _app.setLayout(layout)
ssrContext.nuxt.layout = _app.layoutName ssrContext.nuxt.layout = _app.layoutName
<% } %> <% } %>
@ -170,7 +184,9 @@ export default async (ssrContext) => {
} }
}) })
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') {
app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name }) app.context.error({ statusCode: 500, message: 'Unknown middleware ' + name })
} }
@ -178,8 +194,12 @@ export default async (ssrContext) => {
}) })
await middlewareSeries(midd, app.context) await middlewareSeries(midd, app.context)
// ...If there is a redirect or an error, stop the process // ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp() if (ssrContext.redirected) {
if (ssrContext.nuxt.error) return renderErrorPage() return noopApp()
}
if (ssrContext.nuxt.error) {
return renderErrorPage()
}
<% } %> <% } %>
<% if (features.validate) { %> <% if (features.validate) { %>
@ -211,14 +231,18 @@ export default async (ssrContext) => {
// ...If .validate() returned false // ...If .validate() returned false
if (!isValid) { if (!isValid) {
// Don't server-render the page in generate mode // Don't server-render the page in generate mode
if (ssrContext._generate) ssrContext.nuxt.serverRendered = false if (ssrContext._generate) {
ssrContext.nuxt.serverRendered = false
}
// Render a 404 error page // Render a 404 error page
return render404Page() return render404Page()
} }
<% } %> <% } %>
// If no Components found, returns 404 // If no Components found, returns 404
if (!Components.length) return render404Page() if (!Components.length) {
return render404Page()
}
<% if (features.asyncData || features.fetch) { %> <% if (features.asyncData || features.fetch) { %>
// Call asyncData & fetch hooks on components matched by the route. // Call asyncData & fetch hooks on components matched by the route.
@ -259,8 +283,12 @@ export default async (ssrContext) => {
<% } %> <% } %>
// ...If there is a redirect or an error, stop the process // ...If there is a redirect or an error, stop the process
if (ssrContext.redirected) return noopApp() if (ssrContext.redirected) {
if (ssrContext.nuxt.error) return renderErrorPage() return noopApp()
}
if (ssrContext.nuxt.error) {
return renderErrorPage()
}
// Call beforeNuxtRender methods & add store state // Call beforeNuxtRender methods & add store state
await beforeRender() await beforeRender()

View File

@ -3,7 +3,11 @@ import Vuex from 'vuex'
Vue.use(Vuex) Vue.use(Vuex)
<%
const willResolveStoreModules = storeModules.some(s => s.src.indexOf('index.') !== 0)
if (willResolveStoreModules) { %>
const VUEX_PROPERTIES = ['state', 'getters', 'actions', 'mutations'] const VUEX_PROPERTIES = ['state', 'getters', 'actions', 'mutations']
<% } %>
let store = {} let store = {}
void (function updateModules () { void (function updateModules () {
@ -15,6 +19,7 @@ void (function updateModules() {
// If store is an exported method = classic mode (deprecated) // If store is an exported method = classic mode (deprecated)
<% if (isDev) { %> <% if (isDev) { %>
if (typeof store === 'function') { if (typeof store === 'function') {
<%= isTest ? '// eslint-disable-next-line no-console' : '' %>
return console.warn('Classic mode for store/ is deprecated and will be removed in Nuxt 3.') return console.warn('Classic mode for store/ is deprecated and will be removed in Nuxt 3.')
}<% } %> }<% } %>
@ -47,6 +52,33 @@ export const createStore = store instanceof Function ? store : () => {
}, store)) }, store))
} }
function normalizeRoot (moduleData, filePath) {
moduleData = moduleData.default || moduleData
if (moduleData.commit) {
throw new Error(`[nuxt] ${filePath} should export a method that returns a Vuex instance.`)
}
if (typeof moduleData !== 'function') {
// Avoid TypeError: setting a property that has only a getter when overwriting top level keys
moduleData = Object.assign({}, moduleData)
}
return normalizeModule(moduleData, filePath)
}
function normalizeModule (moduleData, filePath) {
if (moduleData.state && typeof moduleData.state !== 'function') {
<%= isTest ? '// eslint-disable-next-line no-console' : '' %>
console.warn(`'state' should be a method that returns an object in ${filePath}`)
const state = Object.assign({}, moduleData.state)
// Avoid TypeError: setting a property that has only a getter when overwriting top level keys
moduleData = Object.assign({}, moduleData, { state: () => state })
}
return moduleData
}
<% if (willResolveStoreModules) { %>
function resolveStoreModules (moduleData, filename) { function resolveStoreModules (moduleData, filename) {
moduleData = moduleData.default || moduleData moduleData = moduleData.default || moduleData
// Remove store src + extension (./foo/index.js -> foo/index) // Remove store src + extension (./foo/index.js -> foo/index)
@ -87,22 +119,9 @@ function resolveStoreModules(moduleData, filename) {
} }
} }
function normalizeRoot(moduleData, filePath) {
moduleData = moduleData.default || moduleData
if (moduleData.commit) {
throw new Error(`[nuxt] ${filePath} should export a method that returns a Vuex instance.`)
}
if (typeof moduleData !== 'function') {
// Avoid TypeError: setting a property that has only a getter when overwriting top level keys
moduleData = Object.assign({}, moduleData)
}
return normalizeModule(moduleData, filePath)
}
function normalizeState (moduleData, filePath) { function normalizeState (moduleData, filePath) {
if (typeof moduleData !== 'function') { if (typeof moduleData !== 'function') {
<%= isTest ? '// eslint-disable-next-line no-console' : '' %>
console.warn(`${filePath} should export a method that returns an object`) console.warn(`${filePath} should export a method that returns an object`)
const state = Object.assign({}, moduleData) const state = Object.assign({}, moduleData)
return () => state return () => state
@ -110,16 +129,6 @@ function normalizeState(moduleData, filePath) {
return normalizeModule(moduleData, filePath) return normalizeModule(moduleData, filePath)
} }
function normalizeModule(moduleData, filePath) {
if (moduleData.state && typeof moduleData.state !== 'function') {
console.warn(`'state' should be a method that returns an object in ${filePath}`)
const state = Object.assign({}, moduleData.state)
// Avoid TypeError: setting a property that has only a getter when overwriting top level keys
moduleData = Object.assign({}, moduleData, { state: () => state })
}
return moduleData
}
function getStoreModule (storeModule, namespaces, { isProperty = false } = {}) { function getStoreModule (storeModule, namespaces, { isProperty = false } = {}) {
// If ./mutations.js // If ./mutations.js
if (!namespaces.length || (isProperty && namespaces.length === 1)) { if (!namespaces.length || (isProperty && namespaces.length === 1)) {
@ -136,7 +145,9 @@ function getStoreModule(storeModule, namespaces, { isProperty = false } = {}) {
} }
function mergeProperty (storeModule, moduleData, property) { function mergeProperty (storeModule, moduleData, property) {
if (!moduleData) return if (!moduleData) {
return
}
if (property === 'state') { if (property === 'state') {
storeModule.state = moduleData || storeModule.state storeModule.state = moduleData || storeModule.state
@ -144,3 +155,4 @@ function mergeProperty(storeModule, moduleData, property) {
storeModule[property] = Object.assign({}, storeModule[property], moduleData) storeModule[property] = Object.assign({}, storeModule[property], moduleData)
} }
} }
<% } %>

View File

@ -98,7 +98,9 @@
<script> <script>
window.addEventListener('error', function () { window.addEventListener('error', function () {
var e = document.getElementById('nuxt-loading'); var e = document.getElementById('nuxt-loading');
if (e) e.className += ' error'; if (e) {
e.className += ' error';
}
}); });
</script> </script>

View File

@ -21,7 +21,7 @@ describe('nuxt minimal vue-app bundle size limit', () => {
const filter = filename => filename === 'vue-app.nuxt.js' const filter = filename => filename === 'vue-app.nuxt.js'
const legacyResourcesSize = await getResourcesSize(distDir, 'client', { filter }) const legacyResourcesSize = await getResourcesSize(distDir, 'client', { filter })
const LEGACY_JS_RESOURCES_KB_SIZE = 15.8 const LEGACY_JS_RESOURCES_KB_SIZE = 15.2
expect(legacyResourcesSize.uncompressed).toBeWithinSize(LEGACY_JS_RESOURCES_KB_SIZE) expect(legacyResourcesSize.uncompressed).toBeWithinSize(LEGACY_JS_RESOURCES_KB_SIZE)
}) })
}) })

View File

@ -4615,10 +4615,10 @@ eslint-module-utils@^2.4.0:
debug "^2.6.8" debug "^2.6.8"
pkg-dir "^2.0.0" pkg-dir "^2.0.0"
eslint-multiplexer@^1.0.4: eslint-multiplexer@^2.0.0:
version "1.0.4" version "2.0.0"
resolved "https://registry.npmjs.org/eslint-multiplexer/-/eslint-multiplexer-1.0.4.tgz#4dde202fa2c9edc2ee802ab4b8fdb02a49b6d596" resolved "https://registry.npmjs.org/eslint-multiplexer/-/eslint-multiplexer-2.0.0.tgz#34d00218f5027b417b89a4add81f1536d4197a7d"
integrity sha512-KdakcevBFb6n4VQBRY7u+wFqyREzz1QYJRuuPNHUcK5hN1XOikJIEC5Qf+28ZRIvHkoxiw/CW//LNAAyQzxaiQ== integrity sha512-hZA86lQ6d3srMwVlEjYVsX24mk/AImm4zL0r0AR8jNsJYoznQT7O2xgeaT6gNsLIxzRP79VkpeMVRxu4+GRWOA==
dependencies: dependencies:
cross-spawn "^6.0.5" cross-spawn "^6.0.5"
minimist "^1.2.0" minimist "^1.2.0"