Nuxt/packages/vue-app/template/App.js
Sébastien Chopin 917adc0618
feat: options.target and full-static export (#6159)
* feat: add options.target

* fix(lint): lint

* fix(test): update snapshots

* fix(builder): default value for target

* fix(test): fix test

* fix(test): test fixing

* fix: use this.options.target

* fix: final test

* Update packages/vue-renderer/src/renderer.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: Add target option and update banner

* fix(lint): fix

* feat: Add warning when using serverMiddleware in static target

* chore(utils): add TARGETS and MODES as constants

* hotfix: lint

* chore(module): add filename as alias of fileName

* feat: introducing nuxt export and router/routes.json

* hotfix: Fix the linting lord

* chore(core): add comment for filename vs fileName

* fix: use targets constant

* chore: remove warning

* fix: unit testing

* wip: refactor and use TARGETS

* fix: lint

* feat: add target as alias for first arg value

* fix: generate only for SPA

* chore: explain to use nuxt static X

* fix: render SPA fallback on redirect for static target

* fix: lint issue

* fix: only target is useful for now

* wip

* wip: nuxt static export is looking good

* Update packages/generator/src/generator.js

Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com>

* Update packages/cli/src/options/common.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: add options.target

* fix(lint): lint

* fix(test): update snapshots

* fix(builder): default value for target

* fix(test): fix test

* fix(test): test fixing

* fix: use this.options.target

* fix: final test

* Update packages/vue-renderer/src/renderer.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: Add target option and update banner

* fix(lint): fix

* feat: Add warning when using serverMiddleware in static target

* chore(utils): add TARGETS and MODES as constants

* hotfix: lint

* chore(module): add filename as alias of fileName

* feat: introducing nuxt export and router/routes.json

* hotfix: Fix the linting lord

* chore(core): add comment for filename vs fileName

* fix: use targets constant

* chore: remove warning

* fix: unit testing

* wip: refactor and use TARGETS

* fix: lint

* feat: add target as alias for first arg value

* chore: explain to use nuxt static X

* fix: render SPA fallback on redirect for static target

* fix: lint issue

* fix: only target is useful for now

* wip

* wip: nuxt static export is looking good

* Update packages/generator/src/generator.js

Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com>

* Update packages/cli/src/options/common.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* fix: duplicate imports

* chore: don't server render if an error happens on static target

* test: update unit and add export

* lint: fix

* lint: fix

* fix: e2e test

* fix: fallback only for static target

* fix: dev test

* feat: add generate.crawler

* fix: full static is when generate.static is given

* chore: improvements

* fix: Add isFullStatic in nuxt/config.json

* feat: handle fetch for full static

* feat: router.prefetchPayloads for full static

* chore: use fetch in async-data example

* fix: add target only if given

* fix: use created to have access to props in fetchOnServer

* chore: add console.error in dev for easy debugging

* feat: payload smart pre-fetching

* fix: remove alias for target

* fix: increment payloadFetchIndex is static set to false

* chore: lint

* chore: add serve command

* chore: rename universal to server-side

* fix: handle payloadPath on SPA fallback

* fix: lint

* chore lint again

* feat: handle spa fallback

* feat: support string for exclude

* fix: fallback only if no extension or html

* chore: use JSON.stringify() for static target

* chore: lint again, dammit

* chore: fix tests and remove too early return

* fix: early return only for server target

* fix: update tests

* fix: unit tests

* chore: add ssr option

* chore: add logic for ssr option

* fix: #6682

* chore(dx): add next command to run

* fix: lint

* fix: tests

* chore: keep old behaviour for nuxt build in spa

* fix: test again, oh boy

* fix: alright this is good now

* chore: add comment for spa fallback

* chore: move routes.json to dot nuxt dir

* chore: simplify check for promise

* chore: unique lock id

* chore: refactor isFullStatic

* fix: dont set default in build context

* chore: add test for serve

* chore: update tests

* hotfix: lint tests

* chore(dx): improve message for bundling

* feat: js payload extraction with jsonp

* fix: keep serialized session script for legacy generate

* fix: call to setPagePayload from fetchPayload

* use devalue for payload chunks

* feat: add initial load state chunk

* feat: preload payload and state scripts

* fix(vue-app): don't re-render the app if trailing slash on SSG

* hotfix: remove console.log

* chore(dx): add deploy infos for nuxt export

Co-authored-by: Pooya Parsa <pyapar@gmail.com>

* chore: handle fetching payload.js for nuxt state

* chore(dx): error when using nuxt generate and static

* chore: remove static option for clarity

* chore: remove serverless target

* hotfix: lint

* hotfix: unit tests

* chore: update legacy js resource

* chore: remove query params from url in static target

* fix: use globalName and urlJoin

* chore: typo

* feat: previewMode 👀

* chore: rename to enablePreview

* fix: wait next tick to avoid error on spa

* chore: try 1 sec

* hotfix: test only for linux, wtf azure

* refactor: static assets

- generalize logic for modules need emit export static assets
- allow customization for version, dir and base
- serialization logic is only in ssr now

* feat: smart state chunk creates

* fix(client): ignore payload load error

* perf: avoide payload loading for spa initial

* perf: avoid loading failed chunks again

* chore(cli): add simple compression for nuxt serve

* test: update snapshots

* fix version snapshot

* fix(generator): set staticAssetsBase on context only for full static

* fix tests

* fix: honor shouldHashCspScriptSrc

* chore(dx): add log for client-side fallback creation

Co-authored-by: Xin Du (Clark) <clark.duxin@gmail.com>
Co-authored-by: Alexander Lichter <manniL@gmx.net>
Co-authored-by: Pooya Parsa <pooya@pi0.ir>
Co-authored-by: Devon Rueckner <indirectlylit@users.noreply.github.com>
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
2020-05-07 21:08:01 +02:00

326 lines
9.8 KiB
JavaScript

import Vue from 'vue'
<% utilsImports = [
...(features.asyncData || features.fetch) ? [
'getMatchedComponentsInstances',
'getChildrenComponentInstancesUsingFetch',
'promisify',
'globalHandleError',
'urlJoin'
] : [],
...features.layouts ? [
'sanitizeComponent'
]: []
] %>
<% if (utilsImports.length) { %>import { <%= utilsImports.join(', ') %> } from './utils'<% } %>
<% if (features.layouts && components.ErrorPage) { %>import NuxtError from '<%= components.ErrorPage %>'<% } %>
<% if (loading) { %>import NuxtLoading from '<%= (typeof loading === "string" ? loading : "./components/nuxt-loading.vue") %>'<% } %>
<% if (buildIndicator) { %>import NuxtBuildIndicator from './components/nuxt-build-indicator'<% } %>
<% css.forEach((c) => { %>
import '<%= relativeToBuild(resolvePath(c.src || c, { isStyle: true })) %>'
<% }) %>
<% if (features.layouts) { %>
<%= Object.keys(layouts).map((key) => {
if (splitChunks.layouts) {
return `const _${hash(key)} = () => import('${layouts[key]}' /* webpackChunkName: "${wChunk('layouts/' + key)}" */).then(m => sanitizeComponent(m.default || m))`
} else {
return `import _${hash(key)} from '${layouts[key]}'`
}
}).join('\n') %>
<% if (splitChunks.layouts) { %>
let resolvedLayouts = {}
const layouts = { <%= Object.keys(layouts).map(key => `"_${key}": _${hash(key)}`).join(',') %> }<%= isTest ? '// eslint-disable-line' : '' %>
<% } else { %>
const layouts = { <%= Object.keys(layouts).map(key => `"_${key}": sanitizeComponent(_${hash(key)})`).join(',') %> }<%= isTest ? '// eslint-disable-line' : '' %>
<% } %>
<% } %>
export default {
render (h, props) {
<% if (loading) { %>const loadingEl = h('NuxtLoading', { ref: 'loading' })<% } %>
<% if (features.layouts) { %>
<% if (components.ErrorPage) { %>
if (this.nuxt.err && NuxtError) {
const errorLayout = (NuxtError.options || NuxtError).layout
if (errorLayout) {
this.setLayout(
typeof errorLayout === 'function'
? errorLayout.call(NuxtError, this.context)
: errorLayout
)
}
}
<% } %>
const layoutEl = h(this.layout || 'nuxt')
const templateEl = h('div', {
domProps: {
id: '__layout'
},
key: this.layoutName
}, [layoutEl])
<% } else { %>
const templateEl = h('nuxt')
<% } %>
<% if (features.transitions) { %>
const transitionEl = h('transition', {
props: {
name: '<%= layoutTransition.name %>',
mode: '<%= layoutTransition.mode %>'
},
on: {
beforeEnter (el) {
// Ensure to trigger scroll event after calling scrollBehavior
window.<%= globals.nuxt %>.$nextTick(() => {
window.<%= globals.nuxt %>.$emit('triggerScroll')
})
}
}
}, [templateEl])
<% } %>
return h('div', {
domProps: {
id: '<%= globals.id %>'
}
}, [
<% if (loading) { %>loadingEl, <% } %>
<% if (buildIndicator) { %>h(NuxtBuildIndicator), <% } %>
<% if (features.transitions) { %>transitionEl<% } else { %>templateEl<% } %>
])
},
<% if (features.clientOnline || features.layouts) { %>
data: () => ({
<% if (features.clientOnline) { %>
isOnline: true,
<% } %>
<% if (features.layouts) { %>
layout: null,
layoutName: '',
<% } %>
<% if (features.fetch) { %>
nbFetching: 0
<% } %>
}),
<% } %>
beforeCreate () {
Vue.util.defineReactive(this, 'nuxt', this.$options.nuxt)
},
created () {
// Add this.$nuxt in child instances
Vue.prototype.<%= globals.nuxt %> = this
if (process.client) {
// add to window so we can listen when ready
window.<%= globals.nuxt %> = <%= (globals.nuxt !== '$nuxt' ? 'window.$nuxt = ' : '') %>this
<% if (features.clientOnline) { %>
this.refreshOnlineStatus()
// Setup the listeners
window.addEventListener('online', this.refreshOnlineStatus)
window.addEventListener('offline', this.refreshOnlineStatus)
<% } %>
}
// Add $nuxt.error()
this.error = this.nuxt.error
// Add $nuxt.context
this.context = this.$options.context
},
<% if (loading || isFullStatic) { %>
async mounted () {
<% if (loading) { %>this.$loading = this.$refs.loading<% } %>
<% if (isFullStatic) {%>
if (this.isPreview) {
if (this.$store && this.$store._actions.nuxtServerInit) {
<% if (loading) { %>this.$loading.start()<% } %>
await app.$store.dispatch('nuxtServerInit', this.context)
}
await this.refresh()
<% if (loading) { %>this.$loading.finish()<% } %>
}
<% } %>
},
<% } %>
<% if (loading) { %>
watch: {
'nuxt.err': 'errorChanged'
},
<% } %>
<% if (features.clientOnline) { %>
computed: {
isOffline () {
return !this.isOnline
},
<% if (features.fetch) { %>
isFetching () {
return this.nbFetching > 0
},<% } %>
<% if (nuxtOptions.target === 'static') { %>
isPreview () {
return Boolean(this.$options.previewData)
},<% } %>
},
<% } %>
methods: {
<%= isTest ? '/* eslint-disable comma-dangle */' : '' %>
<% if (features.clientOnline) { %>
refreshOnlineStatus () {
if (process.client) {
if (typeof window.navigator.onLine === 'undefined') {
// If the browser doesn't support connection status reports
// assume that we are online because most apps' only react
// when they now that the connection has been interrupted
this.isOnline = true
} else {
this.isOnline = window.navigator.onLine
}
}
},
<% } %>
async refresh () {
<% if (features.asyncData || features.fetch) { %>
const pages = getMatchedComponentsInstances(this.$route)
if (!pages.length) {
return
}
<% if (loading) { %>this.$loading.start()<% } %>
const promises = pages.map((page) => {
const p = []
<% if (features.fetch) { %>
// Old fetch
if (page.$options.fetch && page.$options.fetch.length) {
p.push(promisify(page.$options.fetch, this.context))
}
if (page.$fetch) {
p.push(page.$fetch())
} else {
// Get all component instance to call $fetch
for (const component of getChildrenComponentInstancesUsingFetch(page.$vnode.componentInstance)) {
p.push(component.$fetch())
}
}
<% } %>
<% if (features.asyncData) { %>
if (page.$options.asyncData) {
p.push(
promisify(page.$options.asyncData, this.context)
.then((newData) => {
for (const key in newData) {
Vue.set(page.$data, key, newData[key])
}
})
)
}
<% } %>
return Promise.all(p)
})
try {
await Promise.all(promises)
} catch (error) {
<% if (loading) { %>this.$loading.fail(error)<% } %>
globalHandleError(error)
this.error(error)
}
<% if (loading) { %>this.$loading.finish()<% } %>
<% } %>
},
<% if (loading) { %>
errorChanged () {
if (this.nuxt.err && this.$loading) {
if (this.$loading.fail) {
this.$loading.fail(this.nuxt.err)
}
if (this.$loading.finish) {
this.$loading.finish()
}
}
},
<% } %>
<% if (features.layouts) { %>
<% if (splitChunks.layouts) { %>
setLayout (layout) {
<% if (debug) { %>
if(layout && typeof layout !== 'string') {
throw new Error('[nuxt] Avoid using non-string value as layout property.')
}
<% } %>
if (!layout || !resolvedLayouts['_' + layout]) {
layout = 'default'
}
this.layoutName = layout
let _layout = '_' + layout
this.layout = resolvedLayouts[_layout]
return this.layout
},
loadLayout (layout) {
const undef = !layout
const nonexistent = !(layouts['_' + layout] || resolvedLayouts['_' + layout])
let _layout = '_' + ((undef || nonexistent) ? 'default' : layout)
if (resolvedLayouts[_layout]) {
return Promise.resolve(resolvedLayouts[_layout])
}
return layouts[_layout]()
.then((Component) => {
resolvedLayouts[_layout] = Component
delete layouts[_layout]
return resolvedLayouts[_layout]
})
.catch((e) => {
if (this.<%= globals.nuxt %>) {
return this.<%= globals.nuxt %>.error({ statusCode: 500, message: e.message })
}
})
},
<% } else { %>
setLayout (layout) {
<% if (debug) { %>
if(layout && typeof layout !== 'string') {
throw new Error('[nuxt] Avoid using non-string value as layout property.')
}
<% } %>
if (!layout || !layouts['_' + layout]) {
layout = 'default'
}
this.layoutName = layout
this.layout = layouts['_' + layout]
return this.layout
},
loadLayout (layout) {
if (!layout || !layouts['_' + layout]) {
layout = 'default'
}
return Promise.resolve(layouts['_' + layout])
},
<% } /* splitChunks.layouts */ %>
<% } /* features.layouts */ %>
<% if (isFullStatic) { %>
setPagePayload(payload) {
this._pagePayload = payload
this._payloadFetchIndex = 0
},
async fetchPayload(route) {
route = (route.replace(/\/$/, '') || '/').split('?')[0]
try {
const src = urlJoin(window.__NUXT_STATIC__, route, 'payload.js')
const payload = await window.__NUXT_IMPORT__(route, src)
this.setPagePayload(payload)
return payload
} catch (err) {
this.setPagePayload(false)
throw err
}
}
<% } %>
},
<% if (loading) { %>
components: {
NuxtLoading
}
<% } %>
<%= isTest ? '/* eslint-enable comma-dangle */' : '' %>
}