[READ-ONLY] Mirror of https://github.com/danielroe/nuxt-vue3-module.
0

Configure Feed

Select the types of activity you want to include in your feed.

fix: patch `client.js` rather than hard-code it

Daniel Roe (Jun 8, 2021, 5:00 PM +0100) 3f9b1c52 0fe23175

+28 -964
+1
.gitignore
··· 7 7 .DS_Store 8 8 coverage 9 9 dist 10 + src/templates/client.js
+1
README.md
··· 19 19 ## Known limitations and workarounds 20 20 21 21 - You will need to use `<RouterLink>` instead of `<NuxtLink>` 22 + - This library overrides your `client.js` template from `@nuxt/vue-app` 22 23 23 24 ## Quick setup 24 25
+2
package.json
··· 37 37 "@vue/compiler-sfc": "^3.1.1", 38 38 "@vue/server-renderer": "^3.1.1", 39 39 "chalk": "^4.1.1", 40 + "fs-extra": "^9", 40 41 "upath": "2.0.1", 41 42 "vue": "^3.1.1", 42 43 "vue-loader": "^16.0.0", ··· 53 54 "@nuxt/typescript-build": "2.1.0", 54 55 "@nuxtjs/eslint-config-typescript": "6.0.1", 55 56 "@release-it/conventional-changelog": "2.0.1", 57 + "@types/fs-extra": "^9.0.11", 56 58 "@types/jest": "26.0.23", 57 59 "babel-eslint": "latest", 58 60 "babel-jest": "27.0.2",
+17 -10
yarn.lock
··· 2009 2009 dependencies: 2010 2010 "@types/webpack" "^4" 2011 2011 2012 + "@types/fs-extra@^9.0.11": 2013 + version "9.0.11" 2014 + resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.11.tgz#8cc99e103499eab9f347dbc6ca4e99fb8d2c2b87" 2015 + integrity sha512-mZsifGG4QeQ7hlkhO56u7zt/ycBgGxSVsFI/6lGTU34VtwkiqrrSDgw0+ygs8kFGWcXnFQWMrzF2h7TtDFNixA== 2016 + dependencies: 2017 + "@types/node" "*" 2018 + 2012 2019 "@types/glob@^7.1.1": 2013 2020 version "7.1.3" 2014 2021 resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.1.3.tgz#e6ba80f36b7daad2c685acd9266382e68985c183" ··· 6329 6336 inherits "^2.0.1" 6330 6337 readable-stream "^2.0.0" 6331 6338 6339 + fs-extra@9, fs-extra@^9.0.0, fs-extra@^9.0.1, fs-extra@^9.1.0: 6340 + version "9.1.0" 6341 + resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.1.0.tgz#5954460c764a8da2094ba3554bf839e6b9a7c86d" 6342 + integrity sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ== 6343 + dependencies: 6344 + at-least-node "^1.0.0" 6345 + graceful-fs "^4.2.0" 6346 + jsonfile "^6.0.1" 6347 + universalify "^2.0.0" 6348 + 6332 6349 fs-extra@^10.0.0: 6333 6350 version "10.0.0" 6334 6351 resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-10.0.0.tgz#9ff61b655dde53fb34a82df84bb214ce802e17c1" ··· 6346 6363 graceful-fs "^4.2.0" 6347 6364 jsonfile "^4.0.0" 6348 6365 universalify "^0.1.0" 6349 - 6350 - fs-extra@^9.0.0, fs-extra@^9.0.1, fs-extra@^9.1.0: 6351 - version "9.1.0" 6352 - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.1.0.tgz#5954460c764a8da2094ba3554bf839e6b9a7c86d" 6353 - integrity sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ== 6354 - dependencies: 6355 - at-least-node "^1.0.0" 6356 - graceful-fs "^4.2.0" 6357 - jsonfile "^6.0.1" 6358 - universalify "^2.0.0" 6359 6366 6360 6367 fs-memo@^1.2.0: 6361 6368 version "1.2.0"
+7 -3
src/index.ts
··· 1 1 import { defineNuxtModule, extendBuild } from '@nuxt/kit' 2 + import { readFile, writeFile } from 'fs-extra' 2 3 import type { Configuration } from 'webpack' 3 4 import { bold, greenBright } from 'chalk' 4 5 import VueLoaderPlugin from 'vue-loader/dist/pluginWebpack4' ··· 16 17 17 18 nuxt.options.cli.badgeMessages.push(greenBright(bold('[Vue 3 compatibility build]'))) 18 19 19 - nuxt.hook('build:templates', (templates) => { 20 - templates.templatesFiles.forEach((file) => { 20 + nuxt.hook('build:templates', async (templates) => { 21 + for await (const file of templates.templatesFiles) { 21 22 if (typeof file === 'object' && file.src?.endsWith('template/client.js')) { 23 + let nuxtClientSource = await readFile(file.src, 'utf-8') 24 + nuxtClientSource = nuxtClientSource.replace('$parent.$children.forEach', '$parent.$children.filter(Boolean).forEach') 25 + await writeFile(join(__dirname, './templates/client.js'), nuxtClientSource) 22 26 file.src = join(__dirname, './templates/client.js') 23 27 } 24 - }) 28 + } 25 29 }) 26 30 27 31 nuxt.hook('vite:extend', (ctx) => {
-951
src/templates/client.js
··· 1 - import Vue from 'vue' 2 - <% if (fetch.client) { %>import fetch from 'unfetch'<% } %> 3 - <% if (features.middleware) { %>import middleware from './middleware.js'<% } %> 4 - import { 5 - <% if (features.asyncData) { %>applyAsyncData, 6 - promisify,<% } %> 7 - <% if (features.middleware) { %>middlewareSeries,<% } %> 8 - <% if (features.transitions || (features.middleware && features.layouts)) { %>sanitizeComponent,<% } %> 9 - resolveRouteComponents, 10 - getMatchedComponents, 11 - getMatchedComponentsInstances, 12 - flatMapComponents, 13 - setContext, 14 - <% if (features.transitions || features.asyncData || features.fetch) { %>getLocation,<% } %> 15 - compile, 16 - getQueryDiff, 17 - globalHandleError, 18 - isSamePath, 19 - urlJoin 20 - } from './utils.js' 21 - import { createApp<% if (features.layouts) { %>, NuxtError<% } %> } from './index.js' 22 - <% if (features.fetch) { %>import fetchMixin from './mixins/fetch.client'<% } %> 23 - import NuxtLink from './components/nuxt-link.<%= features.clientPrefetch ? "client" : "server" %>.js' // should be included after ./index.js 24 - <% if (isFullStatic) { %>import { installJsonp } from './jsonp'<% } %> 25 - 26 - <% if (isFullStatic) { %>installJsonp()<% } %> 27 - 28 - <% if (features.fetch) { %> 29 - // Fetch mixin 30 - if (!Vue.__nuxt__fetch__mixin__) { 31 - Vue.mixin(fetchMixin) 32 - Vue.__nuxt__fetch__mixin__ = true 33 - } 34 - <% } %> 35 - 36 - // Component: <NuxtLink> 37 - Vue.component(NuxtLink.name, NuxtLink) 38 - <% if (features.componentAliases) { %>Vue.component('NLink', NuxtLink)<% } %> 39 - 40 - <% if (fetch.client) { %>if (!global.fetch) { global.fetch = fetch }<% } %> 41 - 42 - // Global shared references 43 - let _lastPaths = []<%= isTest ? '// eslint-disable-line no-unused-vars' : '' %> 44 - let app 45 - let router 46 - <% if (store) { %>let store<%= isTest ? '// eslint-disable-line no-unused-vars' : '' %><% } %> 47 - 48 - // Try to rehydrate SSR data from window 49 - const NUXT = window.<%= globals.context %> || {} 50 - 51 - const $config = NUXT.config || {} 52 - if ($config._app) { 53 - __webpack_public_path__ = urlJoin($config._app.cdnURL, $config._app.assetsPath) 54 - } 55 - 56 - Object.assign(Vue.config, <%= serialize(vue.config) %>)<%= isTest ? '// eslint-disable-line' : '' %> 57 - 58 - <% if (nuxtOptions.render.ssrLog) { %> 59 - const logs = NUXT.logs || [] 60 - if (logs.length > 0) { 61 - const ssrLogStyle = 'background: #2E495E;border-radius: 0.5em;color: white;font-weight: bold;padding: 2px 0.5em;' 62 - console.group && console.group<%= nuxtOptions.render.ssrLog === 'collapsed' ? 'Collapsed' : '' %> ('%cNuxt SSR', ssrLogStyle) 63 - logs.forEach(logObj => (console[logObj.type] || console.log)(...logObj.args)) 64 - delete NUXT.logs 65 - console.groupEnd && console.groupEnd() 66 - } 67 - <% } %> 68 - <% if (debug) { %> 69 - // Setup global Vue error handler 70 - if (!Vue.config.$nuxt) { 71 - const defaultErrorHandler = Vue.config.errorHandler 72 - Vue.config.errorHandler = async (err, vm, info, ...rest) => { 73 - // Call other handler if exist 74 - let handled = null 75 - if (typeof defaultErrorHandler === 'function') { 76 - handled = defaultErrorHandler(err, vm, info, ...rest) 77 - } 78 - if (handled === true) { 79 - return handled 80 - } 81 - 82 - if (vm && vm.$root) { 83 - const nuxtApp = Object.keys(Vue.config.$nuxt) 84 - .find(nuxtInstance => vm.$root[nuxtInstance]) 85 - 86 - // Show Nuxt Error Page 87 - if (nuxtApp && vm.$root[nuxtApp].error && info !== 'render function') { 88 - const currentApp = vm.$root[nuxtApp] 89 - <% if (features.layouts) { %> 90 - // Load error layout 91 - let layout = (NuxtError.options || NuxtError).layout 92 - if (typeof layout === 'function') { 93 - layout = layout(currentApp.context) 94 - } 95 - if (layout) { 96 - await currentApp.loadLayout(layout).catch(() => {}) 97 - } 98 - currentApp.setLayout(layout) 99 - <% } %> 100 - currentApp.error(err) 101 - } 102 - } 103 - 104 - if (typeof defaultErrorHandler === 'function') { 105 - return handled 106 - } 107 - 108 - // Log to console 109 - if (process.env.NODE_ENV !== 'production') { 110 - console.error(err) 111 - } else { 112 - console.error(err.message || err) 113 - } 114 - } 115 - Vue.config.$nuxt = {} 116 - } 117 - Vue.config.$nuxt.<%= globals.nuxt %> = true 118 - <% } %> 119 - const errorHandler = Vue.config.errorHandler || console.error 120 - 121 - // Create and mount App 122 - createApp(null, NUXT.config).then(mountApp).catch(errorHandler) 123 - 124 - <% if (features.transitions) { %> 125 - function componentOption (component, key, ...args) { 126 - if (!component || !component.options || !component.options[key]) { 127 - return {} 128 - } 129 - const option = component.options[key] 130 - if (typeof option === 'function') { 131 - return option(...args) 132 - } 133 - return option 134 - } 135 - 136 - function mapTransitions (toComponents, to, from) { 137 - const componentTransitions = (component) => { 138 - const transition = componentOption(component, 'transition', to, from) || {} 139 - return (typeof transition === 'string' ? { name: transition } : transition) 140 - } 141 - 142 - const fromComponents = from ? getMatchedComponents(from) : [] 143 - const maxDepth = Math.max(toComponents.length, fromComponents.length) 144 - 145 - const mergedTransitions = [] 146 - for (let i=0; i<maxDepth; i++) { 147 - // Clone original objects to prevent overrides 148 - const toTransitions = Object.assign({}, componentTransitions(toComponents[i])) 149 - const transitions = Object.assign({}, componentTransitions(fromComponents[i])) 150 - 151 - // Combine transitions & prefer `leave` properties of "from" route 152 - Object.keys(toTransitions) 153 - .filter(key => typeof toTransitions[key] !== 'undefined' && !key.toLowerCase().includes('leave')) 154 - .forEach((key) => { transitions[key] = toTransitions[key] }) 155 - 156 - mergedTransitions.push(transitions) 157 - } 158 - return mergedTransitions 159 - } 160 - <% } %> 161 - async function loadAsyncComponents (to, from, next) { 162 - // Check if route changed (this._routeChanged), only if the page is not an error (for validate()) 163 - this._routeChanged = Boolean(app.nuxt.err) || from.name !== to.name 164 - this._paramChanged = !this._routeChanged && from.path !== to.path 165 - this._queryChanged = !this._paramChanged && from.fullPath !== to.fullPath 166 - this._diffQuery = (this._queryChanged ? getQueryDiff(to.query, from.query) : []) 167 - 168 - <% if (loading) { %> 169 - if ((this._routeChanged || this._paramChanged) && this.$loading.start && !this.$loading.manual) { 170 - this.$loading.start() 171 - } 172 - <% } %> 173 - 174 - try { 175 - if (this._queryChanged) { 176 - const Components = await resolveRouteComponents( 177 - to, 178 - (Component, instance) => ({ Component, instance }) 179 - ) 180 - // Add a marker on each component that it needs to refresh or not 181 - const startLoader = Components.some(({ Component, instance }) => { 182 - const watchQuery = Component.options.watchQuery 183 - if (watchQuery === true) { 184 - return true 185 - } 186 - if (Array.isArray(watchQuery)) { 187 - return watchQuery.some(key => this._diffQuery[key]) 188 - } 189 - if (typeof watchQuery === 'function') { 190 - return watchQuery.apply(instance, [to.query, from.query]) 191 - } 192 - return false 193 - }) 194 - <% if (loading) { %> 195 - if (startLoader && this.$loading.start && !this.$loading.manual) { 196 - this.$loading.start() 197 - } 198 - <% } %> 199 - } 200 - // Call next() 201 - next() 202 - } catch (error) { 203 - const err = error || {} 204 - const statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500 205 - const message = err.message || '' 206 - 207 - // Handle chunk loading errors 208 - // This may be due to a new deployment or a network problem 209 - if (/^Loading( CSS)? chunk (\d)+ failed\./.test(message)) { 210 - window.location.reload(true /* skip cache */) 211 - return // prevent error page blinking for user 212 - } 213 - 214 - this.error({ statusCode, message }) 215 - this.<%= globals.nuxt %>.$emit('routeChanged', to, from, err) 216 - next() 217 - } 218 - } 219 - 220 - <% if (features.transitions || features.asyncData || features.fetch) { %> 221 - function applySSRData (Component, ssrData) { 222 - <% if (features.asyncData) { %> 223 - if (NUXT.serverRendered && ssrData) { 224 - applyAsyncData(Component, ssrData) 225 - } 226 - <% } %> 227 - Component._Ctor = Component 228 - return Component 229 - } 230 - 231 - // Get matched components 232 - function resolveComponents (route) { 233 - return flatMapComponents(route, async (Component, _, match, key, index) => { 234 - // If component is not resolved yet, resolve it 235 - if (typeof Component === 'function' && !Component.options) { 236 - Component = await Component() 237 - } 238 - // Sanitize it and save it 239 - const _Component = applySSRData(sanitizeComponent(Component), NUXT.data ? NUXT.data[index] : null) 240 - match.components[key] = _Component 241 - return _Component 242 - }) 243 - } 244 - <% } %> 245 - 246 - <% if (features.middleware) { %> 247 - function callMiddleware (Components, context, layout) { 248 - let midd = <%= devalue(router.middleware) %><%= isTest ? '// eslint-disable-line' : '' %> 249 - let unknownMiddleware = false 250 - 251 - <% if (features.layouts) { %> 252 - // If layout is undefined, only call global middleware 253 - if (typeof layout !== 'undefined') { 254 - midd = [] // Exclude global middleware if layout defined (already called before) 255 - layout = sanitizeComponent(layout) 256 - if (layout.options.middleware) { 257 - midd = midd.concat(layout.options.middleware) 258 - } 259 - Components.forEach((Component) => { 260 - if (Component.options.middleware) { 261 - midd = midd.concat(Component.options.middleware) 262 - } 263 - }) 264 - } 265 - <% } %> 266 - 267 - midd = midd.map((name) => { 268 - if (typeof name === 'function') { 269 - return name 270 - } 271 - if (typeof middleware[name] !== 'function') { 272 - unknownMiddleware = true 273 - this.error({ statusCode: 500, message: 'Unknown middleware ' + name }) 274 - } 275 - return middleware[name] 276 - }) 277 - 278 - if (unknownMiddleware) { 279 - return 280 - } 281 - return middlewareSeries(midd, context) 282 - } 283 - <% } else if (isDev) { 284 - // This is a placeholder function mainly so we dont have to 285 - // refactor the promise chain in addHotReload() 286 - %> 287 - function callMiddleware () { 288 - return Promise.resolve(true) 289 - } 290 - <% } %> 291 - async function render (to, from, next) { 292 - if (this._routeChanged === false && this._paramChanged === false && this._queryChanged === false) { 293 - return next() 294 - } 295 - // Handle first render on SPA mode 296 - let spaFallback = false 297 - if (to === from) { 298 - _lastPaths = [] 299 - spaFallback = true 300 - } else { 301 - const fromMatches = [] 302 - _lastPaths = getMatchedComponents(from, fromMatches).map((Component, i) => { 303 - return compile(from.matched[fromMatches[i]].path)(from.params) 304 - }) 305 - } 306 - 307 - // nextCalled is true when redirected 308 - let nextCalled = false 309 - const _next = (path) => { 310 - <% if (loading) { %> 311 - if (from.path === path.path && this.$loading.finish) { 312 - this.$loading.finish() 313 - } 314 - <% } %> 315 - <% if (loading) { %> 316 - if (from.path !== path.path && this.$loading.pause) { 317 - this.$loading.pause() 318 - } 319 - <% } %> 320 - if (nextCalled) { 321 - return 322 - } 323 - 324 - nextCalled = true 325 - next(path) 326 - } 327 - 328 - // Update context 329 - await setContext(app, { 330 - route: to, 331 - from, 332 - next: _next.bind(this) 333 - }) 334 - this._dateLastError = app.nuxt.dateErr 335 - this._hadError = Boolean(app.nuxt.err) 336 - 337 - // Get route's matched components 338 - const matches = [] 339 - const Components = getMatchedComponents(to, matches) 340 - 341 - // If no Components matched, generate 404 342 - if (!Components.length) { 343 - <% if (features.middleware) { %> 344 - // Default layout 345 - await callMiddleware.call(this, Components, app.context) 346 - if (nextCalled) { 347 - return 348 - } 349 - <% } %> 350 - 351 - <% if (features.layouts) { %> 352 - // Load layout for error page 353 - const errorLayout = (NuxtError.options || NuxtError).layout 354 - const layout = await this.loadLayout( 355 - typeof errorLayout === 'function' 356 - ? errorLayout.call(NuxtError, app.context) 357 - : errorLayout 358 - ) 359 - <% } %> 360 - 361 - <% if (features.middleware) { %> 362 - await callMiddleware.call(this, Components, app.context, layout) 363 - if (nextCalled) { 364 - return 365 - } 366 - <% } %> 367 - 368 - // Show error page 369 - app.context.error({ statusCode: 404, message: '<%= messages.error_404 %>' }) 370 - return next() 371 - } 372 - 373 - <% if (features.asyncData || features.fetch) { %> 374 - // Update ._data and other properties if hot reloaded 375 - Components.forEach((Component) => { 376 - if (Component._Ctor && Component._Ctor.options) { 377 - <% if (features.asyncData) { %>Component.options.asyncData = Component._Ctor.options.asyncData<% } %> 378 - <% if (features.fetch) { %>Component.options.fetch = Component._Ctor.options.fetch<% } %> 379 - } 380 - }) 381 - <% } %> 382 - 383 - <% if (features.transitions) { %> 384 - // Apply transitions 385 - this.setTransitions(mapTransitions(Components, to, from)) 386 - <% } %> 387 - try { 388 - <% if (features.middleware) { %> 389 - // Call middleware 390 - await callMiddleware.call(this, Components, app.context) 391 - if (nextCalled) { 392 - return 393 - } 394 - if (app.context._errored) { 395 - return next() 396 - } 397 - <% } %> 398 - 399 - <% if (features.layouts) { %> 400 - // Set layout 401 - let layout = Components[0].options.layout 402 - if (typeof layout === 'function') { 403 - layout = layout(app.context) 404 - } 405 - layout = await this.loadLayout(layout) 406 - <% } %> 407 - 408 - <% if (features.middleware) { %> 409 - // Call middleware for layout 410 - await callMiddleware.call(this, Components, app.context, layout) 411 - if (nextCalled) { 412 - return 413 - } 414 - if (app.context._errored) { 415 - return next() 416 - } 417 - <% } %> 418 - 419 - 420 - <% if (features.validate) { %> 421 - // Call .validate() 422 - let isValid = true 423 - try { 424 - for (const Component of Components) { 425 - if (typeof Component.options.validate !== 'function') { 426 - continue 427 - } 428 - 429 - isValid = await Component.options.validate(app.context) 430 - 431 - if (!isValid) { 432 - break 433 - } 434 - } 435 - } catch (validationError) { 436 - // ...If .validate() threw an error 437 - this.error({ 438 - statusCode: validationError.statusCode || '500', 439 - message: validationError.message 440 - }) 441 - return next() 442 - } 443 - 444 - // ...If .validate() returned false 445 - if (!isValid) { 446 - this.error({ statusCode: 404, message: '<%= messages.error_404 %>' }) 447 - return next() 448 - } 449 - <% } %> 450 - 451 - <% if (features.asyncData || features.fetch) { %> 452 - let instances 453 - // Call asyncData & fetch hooks on components matched by the route. 454 - await Promise.all(Components.map(async (Component, i) => { 455 - // Check if only children route changed 456 - Component._path = compile(to.matched[matches[i]].path)(to.params) 457 - Component._dataRefresh = false 458 - const childPathChanged = Component._path !== _lastPaths[i] 459 - // Refresh component (call asyncData & fetch) when: 460 - // Route path changed part includes current component 461 - // Or route param changed part includes current component and watchParam is not `false` 462 - // Or route query is changed and watchQuery returns `true` 463 - if (this._routeChanged && childPathChanged) { 464 - Component._dataRefresh = true 465 - } else if (this._paramChanged && childPathChanged) { 466 - const watchParam = Component.options.watchParam 467 - Component._dataRefresh = watchParam !== false 468 - } else if (this._queryChanged) { 469 - const watchQuery = Component.options.watchQuery 470 - if (watchQuery === true) { 471 - Component._dataRefresh = true 472 - } else if (Array.isArray(watchQuery)) { 473 - Component._dataRefresh = watchQuery.some(key => this._diffQuery[key]) 474 - } else if (typeof watchQuery === 'function') { 475 - if (!instances) { 476 - instances = getMatchedComponentsInstances(to) 477 - } 478 - Component._dataRefresh = watchQuery.apply(instances[i], [to.query, from.query]) 479 - } 480 - } 481 - if (!this._hadError && this._isMounted && !Component._dataRefresh) { 482 - return 483 - } 484 - 485 - const promises = [] 486 - 487 - <% if (features.asyncData) { %> 488 - const hasAsyncData = ( 489 - Component.options.asyncData && 490 - typeof Component.options.asyncData === 'function' 491 - ) 492 - <% } else { %> 493 - const hasAsyncData = false 494 - <% } %> 495 - 496 - <% if (features.fetch) { %> 497 - const hasFetch = Boolean(Component.options.fetch) && Component.options.fetch.length 498 - <% } else { %> 499 - const hasFetch = false 500 - <% } %> 501 - 502 - <% if (loading) { %> 503 - const loadingIncrease = (hasAsyncData && hasFetch) ? 30 : 45 504 - <% } %> 505 - 506 - <% if (features.asyncData) { %> 507 - // Call asyncData(context) 508 - if (hasAsyncData) { 509 - <% if (isFullStatic) { %> 510 - let promise 511 - 512 - if (this.isPreview || spaFallback) { 513 - promise = promisify(Component.options.asyncData, app.context) 514 - } else { 515 - promise = this.fetchPayload(to.path) 516 - .then(payload => payload.data[i]) 517 - .catch(_err => promisify(Component.options.asyncData, app.context)) // Fallback 518 - } 519 - <% } else { %> 520 - const promise = promisify(Component.options.asyncData, app.context) 521 - <% } %> 522 - promise.then((asyncDataResult) => { 523 - applyAsyncData(Component, asyncDataResult) 524 - <% if (loading) { %> 525 - if (this.$loading.increase) { 526 - this.$loading.increase(loadingIncrease) 527 - } 528 - <% } %> 529 - }) 530 - promises.push(promise) 531 - } 532 - <% } %> 533 - 534 - <% if (isFullStatic && store) { %> 535 - if (!this.isPreview && !spaFallback) { 536 - // Replay store mutations, catching to avoid error page on SPA fallback 537 - promises.push(this.fetchPayload(to.path).then(payload => { 538 - payload.mutations.forEach(m => { this.$store.commit(m[0], m[1]) }) 539 - }).catch(err => null)) 540 - } 541 - <% } %> 542 - 543 - // Check disabled page loading 544 - this.$loading.manual = Component.options.loading === false 545 - 546 - <% if (features.fetch) { %> 547 - <% if (isFullStatic) { %> 548 - if (!this.isPreview && !spaFallback) { 549 - // Catching the error here for letting the SPA fallback and normal fetch behaviour 550 - promises.push(this.fetchPayload(to.path).catch(err => null)) 551 - } 552 - <% } %> 553 - // Call fetch(context) 554 - if (hasFetch) { 555 - let p = Component.options.fetch(app.context) 556 - if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) { 557 - p = Promise.resolve(p) 558 - } 559 - p.then((fetchResult) => { 560 - <% if (loading) { %> 561 - if (this.$loading.increase) { 562 - this.$loading.increase(loadingIncrease) 563 - } 564 - <% } %> 565 - }) 566 - promises.push(p) 567 - } 568 - <% } %> 569 - 570 - return Promise.all(promises) 571 - })) 572 - <% } %> 573 - 574 - // If not redirected 575 - if (!nextCalled) { 576 - <% if (loading) { %> 577 - if (this.$loading.finish && !this.$loading.manual) { 578 - this.$loading.finish() 579 - } 580 - <% } %> 581 - next() 582 - } 583 - 584 - } catch (err) { 585 - const error = err || {} 586 - if (error.message === 'ERR_REDIRECT') { 587 - return this.<%= globals.nuxt %>.$emit('routeChanged', to, from, error) 588 - } 589 - _lastPaths = [] 590 - 591 - globalHandleError(error) 592 - 593 - <% if (features.layouts) { %> 594 - // Load error layout 595 - let layout = (NuxtError.options || NuxtError).layout 596 - if (typeof layout === 'function') { 597 - layout = layout(app.context) 598 - } 599 - await this.loadLayout(layout) 600 - <% } %> 601 - 602 - this.error(error) 603 - this.<%= globals.nuxt %>.$emit('routeChanged', to, from, error) 604 - next() 605 - } 606 - } 607 - 608 - // Fix components format in matched, it's due to code-splitting of vue-router 609 - function normalizeComponents (to, ___) { 610 - flatMapComponents(to, (Component, _, match, key) => { 611 - if (typeof Component === 'object' && !Component.options) { 612 - // Updated via vue-router resolveAsyncComponents() 613 - Component = Vue.extend(Component) 614 - Component._Ctor = Component 615 - match.components[key] = Component 616 - } 617 - return Component 618 - }) 619 - } 620 - 621 - <% if (features.layouts) { %> 622 - <% if (splitChunks.layouts) { %>async <% } %>function setLayoutForNextPage (to) { 623 - // Set layout 624 - let hasError = Boolean(this.$options.nuxt.err) 625 - if (this._hadError && this._dateLastError === this.$options.nuxt.dateErr) { 626 - hasError = false 627 - } 628 - let layout = hasError 629 - ? (NuxtError.options || NuxtError).layout 630 - : to.matched[0].components.default.options.layout 631 - 632 - if (typeof layout === 'function') { 633 - layout = layout(app.context) 634 - } 635 - <% if (splitChunks.layouts) { %> 636 - await this.loadLayout(layout) 637 - <% } %> 638 - this.setLayout(layout) 639 - } 640 - <% } %> 641 - 642 - function checkForErrors (app) { 643 - // Hide error component if no error 644 - if (app._hadError && app._dateLastError === app.$options.nuxt.dateErr) { 645 - app.error() 646 - } 647 - } 648 - 649 - // When navigating on a different route but the same component is used, Vue.js 650 - // Will not update the instance data, so we have to update $data ourselves 651 - function fixPrepatch (to, ___) { 652 - if (this._routeChanged === false && this._paramChanged === false && this._queryChanged === false) { 653 - return 654 - } 655 - 656 - const instances = getMatchedComponentsInstances(to) 657 - const Components = getMatchedComponents(to) 658 - 659 - let triggerScroll = <%= features.transitions ? 'false' : 'true' %> 660 - 661 - Vue.nextTick(() => { 662 - instances.forEach((instance, i) => { 663 - if (!instance || instance._isDestroyed) { 664 - return 665 - } 666 - 667 - if ( 668 - instance.constructor._dataRefresh && 669 - Components[i] === instance.constructor && 670 - instance.$vnode.data.keepAlive !== true && 671 - typeof instance.constructor.options.data === 'function' 672 - ) { 673 - const newData = instance.constructor.options.data.call(instance) 674 - for (const key in newData) { 675 - Vue.set(instance.$data, key, newData[key]) 676 - } 677 - 678 - triggerScroll = true 679 - } 680 - }) 681 - 682 - if (triggerScroll) { 683 - // Ensure to trigger scroll event after calling scrollBehavior 684 - window.<%= globals.nuxt %>.$nextTick(() => { 685 - window.<%= globals.nuxt %>.$emit('triggerScroll') 686 - }) 687 - } 688 - 689 - checkForErrors(this) 690 - <% if (isDev) { %> 691 - // Hot reloading 692 - setTimeout(() => hotReloadAPI(this), 100) 693 - <% } %> 694 - }) 695 - } 696 - 697 - function nuxtReady (_app) { 698 - window.<%= globals.readyCallback %>Cbs.forEach((cb) => { 699 - if (typeof cb === 'function') { 700 - cb(_app) 701 - } 702 - }) 703 - // Special JSDOM 704 - if (typeof window.<%= globals.loadedCallback %> === 'function') { 705 - window.<%= globals.loadedCallback %>(_app) 706 - } 707 - // Add router hooks 708 - router.afterEach((to, from) => { 709 - // Wait for fixPrepatch + $data updates 710 - Vue.nextTick(() => _app.<%= globals.nuxt %>.$emit('routeChanged', to, from)) 711 - }) 712 - } 713 - 714 - <% if (isDev) { %> 715 - const noopData = () => { return {} } 716 - const noopFetch = () => {} 717 - 718 - // Special hot reload with asyncData(context) 719 - function getNuxtChildComponents ($parent, $components = []) { 720 - $parent.$children.filter(Boolean).forEach(($child) => { 721 - if ($child.$vnode && $child.$vnode.data.nuxtChild && !$components.find(c =>(c.$options.__file === $child.$options.__file))) { 722 - $components.push($child) 723 - } 724 - if ($child.$children && $child.$children.length) { 725 - getNuxtChildComponents($child, $components) 726 - } 727 - }) 728 - 729 - return $components 730 - } 731 - 732 - function hotReloadAPI(_app) { 733 - if (!module.hot) return 734 - 735 - let $components = getNuxtChildComponents(_app.<%= globals.nuxt %>, []) 736 - 737 - $components.forEach(addHotReload.bind(_app)) 738 - } 739 - 740 - function addHotReload ($component, depth) { 741 - if ($component.$vnode.data._hasHotReload) return 742 - $component.$vnode.data._hasHotReload = true 743 - 744 - var _forceUpdate = $component.$forceUpdate.bind($component.$parent) 745 - 746 - $component.$vnode.context.$forceUpdate = async () => { 747 - let Components = getMatchedComponents(router.currentRoute) 748 - let Component = Components[depth] 749 - if (!Component) { 750 - return _forceUpdate() 751 - } 752 - if (typeof Component === 'object' && !Component.options) { 753 - // Updated via vue-router resolveAsyncComponents() 754 - Component = Vue.extend(Component) 755 - Component._Ctor = Component 756 - } 757 - this.error() 758 - let promises = [] 759 - const next = function (path) { 760 - <%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %> 761 - router.push(path) 762 - } 763 - await setContext(app, { 764 - route: router.currentRoute, 765 - isHMR: true, 766 - next: next.bind(this) 767 - }) 768 - const context = app.context 769 - 770 - <% if (loading) { %> 771 - if (this.$loading.start && !this.$loading.manual) { 772 - this.$loading.start() 773 - } 774 - <% } %> 775 - 776 - callMiddleware.call(this, Components, context) 777 - .then(() => { 778 - <% if (features.layouts) { %> 779 - // If layout changed 780 - if (depth !== 0) { 781 - return 782 - } 783 - 784 - let layout = Component.options.layout || 'default' 785 - if (typeof layout === 'function') { 786 - layout = layout(context) 787 - } 788 - if (this.layoutName === layout) { 789 - return 790 - } 791 - let promise = this.loadLayout(layout) 792 - promise.then(() => { 793 - this.setLayout(layout) 794 - Vue.nextTick(() => hotReloadAPI(this)) 795 - }) 796 - return promise 797 - <% } else { %> 798 - return 799 - <% } %> 800 - }) 801 - <% if (features.layouts) { %> 802 - .then(() => { 803 - return callMiddleware.call(this, Components, context, this.layout) 804 - }) 805 - <% } %> 806 - .then(() => { 807 - <% if (features.asyncData) { %> 808 - // Call asyncData(context) 809 - let pAsyncData = promisify(Component.options.asyncData || noopData, context) 810 - pAsyncData.then((asyncDataResult) => { 811 - applyAsyncData(Component, asyncDataResult) 812 - <%= (loading ? 'this.$loading.increase && this.$loading.increase(30)' : '') %> 813 - }) 814 - promises.push(pAsyncData) 815 - <% } %> 816 - 817 - <% if (features.fetch) { %> 818 - // Call fetch() 819 - Component.options.fetch = Component.options.fetch || noopFetch 820 - let pFetch = Component.options.fetch.length && Component.options.fetch(context) 821 - if (!pFetch || (!(pFetch instanceof Promise) && (typeof pFetch.then !== 'function'))) { pFetch = Promise.resolve(pFetch) } 822 - <%= (loading ? 'pFetch.then(() => this.$loading.increase && this.$loading.increase(30))' : '') %> 823 - promises.push(pFetch) 824 - <% } %> 825 - return Promise.all(promises) 826 - }) 827 - .then(() => { 828 - <%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %> 829 - _forceUpdate() 830 - setTimeout(() => hotReloadAPI(this), 100) 831 - }) 832 - } 833 - } 834 - <% } %> 835 - 836 - async function mountApp (__app) { 837 - // Set global variables 838 - app = __app.app 839 - router = __app.router 840 - <% if (store) { %>store = __app.store<% } %> 841 - 842 - // Create Vue instance 843 - const _app = new Vue(app) 844 - 845 - <% if (isFullStatic) { %> 846 - // Load page chunk 847 - if (!NUXT.data && NUXT.serverRendered) { 848 - try { 849 - const payload = await _app.fetchPayload(NUXT.routePath || _app.context.route.path) 850 - Object.assign(NUXT, payload) 851 - } catch (err) {} 852 - } 853 - <% } %> 854 - 855 - <% if (features.layouts && mode !== 'spa') { %> 856 - // Load layout 857 - const layout = NUXT.layout || 'default' 858 - await _app.loadLayout(layout) 859 - _app.setLayout(layout) 860 - <% } %> 861 - 862 - // Mounts Vue app to DOM element 863 - const mount = () => { 864 - _app.$mount('#<%= globals.id %>') 865 - 866 - // Add afterEach router hooks 867 - router.afterEach(normalizeComponents) 868 - <% if (features.layouts) { %> 869 - router.afterEach(setLayoutForNextPage.bind(_app)) 870 - <% } %> 871 - router.afterEach(fixPrepatch.bind(_app)) 872 - 873 - // Listen for first Vue update 874 - Vue.nextTick(() => { 875 - // Call window.{{globals.readyCallback}} callbacks 876 - nuxtReady(_app) 877 - <% if (isDev) { %> 878 - // Enable hot reloading 879 - hotReloadAPI(_app) 880 - <% } %> 881 - }) 882 - } 883 - <% if (features.transitions) { %> 884 - // Resolve route components 885 - const Components = await Promise.all(resolveComponents(app.context.route)) 886 - 887 - // Enable transitions 888 - _app.setTransitions = _app.$options.nuxt.setTransitions.bind(_app) 889 - if (Components.length) { 890 - _app.setTransitions(mapTransitions(Components, router.currentRoute)) 891 - _lastPaths = router.currentRoute.matched.map(route => compile(route.path)(router.currentRoute.params)) 892 - } 893 - <% } else if (features.asyncData || features.fetch) { %> 894 - await Promise.all(resolveComponents(app.context.route)) 895 - <% } %> 896 - // Initialize error handler 897 - _app.$loading = {} // To avoid error while _app.$nuxt does not exist 898 - if (NUXT.error) { 899 - _app.error(NUXT.error) 900 - } 901 - 902 - // Add beforeEach router hooks 903 - router.beforeEach(loadAsyncComponents.bind(_app)) 904 - router.beforeEach(render.bind(_app)) 905 - 906 - // Fix in static: remove trailing slash to force hydration 907 - // Full static, if server-rendered: hydrate, to allow custom redirect to generated page 908 - <% if (isFullStatic) { %> 909 - if (NUXT.serverRendered) { 910 - return mount() 911 - } 912 - <% } else { %> 913 - // Fix in static: remove trailing slash to force hydration 914 - if (NUXT.serverRendered && isSamePath(NUXT.routePath, _app.context.route.path)) { 915 - return mount() 916 - } 917 - <% } %> 918 - 919 - // First render on client-side 920 - const clientFirstMount = () => { 921 - normalizeComponents(router.currentRoute, router.currentRoute) 922 - setLayoutForNextPage.call(_app, router.currentRoute) 923 - checkForErrors(_app) 924 - // Don't call fixPrepatch.call(_app, router.currentRoute, router.currentRoute) since it's first render 925 - mount() 926 - } 927 - 928 - // fix: force next tick to avoid having same timestamp when an error happen on spa fallback 929 - await new Promise(resolve => setTimeout(resolve, 0)) 930 - render.call(_app, router.currentRoute, router.currentRoute, (path) => { 931 - // If not redirected 932 - if (!path) { 933 - clientFirstMount() 934 - return 935 - } 936 - 937 - // Add a one-time afterEach hook to 938 - // mount the app wait for redirect and route gets resolved 939 - const unregisterHook = router.afterEach((to, from) => { 940 - unregisterHook() 941 - clientFirstMount() 942 - }) 943 - 944 - // Push the path and let route to be resolved 945 - router.push(path, undefined, (err) => { 946 - if (err) { 947 - errorHandler(err) 948 - } 949 - }) 950 - }) 951 - }