refactor: rename app to vueApp (#1177)

This commit is contained in:
pooya parsa 2021-10-18 20:31:37 +02:00 committed by GitHub
parent 4cff21005f
commit 035e9b5e8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 120 additions and 105 deletions

View File

@ -3,8 +3,8 @@ import { createHooks } from 'hookable/dist/index.mjs'
import { setNuxtAppInstance } from '#app'
export default (ctx, inject) => {
const nuxt = {
app: {
const nuxtApp = {
vueApp: {
component: Vue.component.bind(Vue),
config: {
globalProperties: {}
@ -23,26 +23,26 @@ export default (ctx, inject) => {
globalName: 'nuxt',
payload: process.client ? ctx.nuxtState : ctx.ssrContext.nuxt,
isHydrating: ctx.isHMR,
legacyNuxt: ctx.app
nuxt2Context: ctx
}
nuxt.hooks = createHooks()
nuxt.hook = nuxt.hooks.hook
nuxt.callHook = nuxt.hooks.callHook
nuxtApp.hooks = createHooks()
nuxtApp.hook = nuxtApp.hooks.hook
nuxtApp.callHook = nuxtApp.hooks.callHook
if (!Array.isArray(ctx.app.created)) {
ctx.app.created = [ctx.app.created]
}
if (process.server) {
nuxt.ssrContext = ctx.ssrContext
nuxtApp.ssrContext = ctx.ssrContext
}
ctx.app.created.push(function () {
nuxt.legacyApp = this
nuxtApp.vue2App = this
})
setNuxtAppInstance(nuxt)
setNuxtAppInstance(nuxtApp)
inject('_nuxtApp', nuxt)
inject('_nuxtApp', nuxtApp)
}

View File

@ -8,9 +8,26 @@ export const defineNuxtComponent = defineComponent
export interface RuntimeNuxtHooks { }
export interface VueAppCompat {
component: Vue['component'],
config: {
globalProperties: any
[key: string]: any
},
directive: Vue['directive'],
mixin: Vue['mixin'],
mount: Vue['mount'],
provide: (name: string, value: any) => void,
unmount: Vue['unmount'],
use: Vue['use']
version: string
}
export interface NuxtAppCompat {
legacyNuxt: Vue
legacyApp: ComponentOptions<Vue>
nuxt2Context: Vue
vue2App: ComponentOptions<Vue>
vueApp: VueAppCompat
globalName: string

View File

@ -153,10 +153,10 @@ export const useContext = () => {
const nuxt = useNuxtApp()
return {
...nuxt.legacyNuxt.context,
...nuxt.nuxt2App.context,
route: computed(() => route),
query: computed(() => route.value.query),
from: computed(() => nuxt.legacyNuxt.context.from),
from: computed(() => nuxt.nuxt2App.context.from),
params: computed(() => route.value.params)
}
}
@ -329,7 +329,7 @@ function getKey (vm) {
const getCounter = createGetCounter(
process.server
? vm.$ssrContext.fetchCounters
: nuxt.legacyApp._fetchCounters,
: nuxt.vue2App._fetchCounters,
defaultKey
)

View File

@ -3,9 +3,9 @@ import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin((nuxt) => {
nuxt._setupFns = []
const _originalSetup = nuxt.legacyNuxt.setup
const _originalSetup = nuxt.nuxt2Context.app.setup
nuxt.legacyNuxt.setup = function (...args) {
nuxt.nuxt2Context.app.setup = function (...args) {
const result = _originalSetup instanceof Function ? _originalSetup(...args) : {}
for (const fn of nuxt._setupFns) {
Object.assign(result, fn.call(this, ...args))

View File

@ -12,32 +12,32 @@ export const useHydration = mock()
// Runtime config helper
export const useRuntimeConfig = () => {
const app = useNuxtApp().legacyApp
if (!app._$config) {
app._$config = reactive(app.$config)
const nuxtApp = useNuxtApp()
if (!nuxtApp.$config) {
nuxtApp.$config = reactive(nuxtApp.nuxt2Context.app.$config)
}
return app._$config
return nuxtApp.$config
}
// Auto-import equivalents for `vue-router`
export const useRouter = () => {
return useNuxtApp()?.legacyNuxt.router as VueRouter
return useNuxtApp()?.nuxt2Context.app.router as VueRouter
}
// This provides an equivalent interface to `vue-router` (unlike legacy implementation)
export const useRoute = () => {
const nuxt = useNuxtApp()
const nuxtApp = useNuxtApp()
if (!nuxt._route) {
Object.defineProperty(nuxt, '__route', {
get: () => nuxt.legacyNuxt.context.route
if (!nuxtApp._route) {
Object.defineProperty(nuxtApp, '__route', {
get: () => nuxtApp.nuxt2Context.app.context.route
})
nuxt._route = reactive(nuxt.__route)
nuxtApp._route = reactive(nuxtApp.__route)
const router = useRouter()
router.afterEach(route => Object.assign(nuxt._route, route))
router.afterEach(route => Object.assign(nuxtApp._route, route))
}
return nuxt._route as Route
return nuxtApp._route as Route
}
// payload.state is used for vuex by nuxt 2

View File

@ -14,16 +14,16 @@ const plugins = normalizePlugins(_plugins)
if (process.server) {
entry = async function createNuxtAppServer (ssrContext: CreateOptions['ssrContext'] = {}) {
const app = createApp(RootComponent)
app.component('App', AppComponent)
const vueApp = createApp(RootComponent)
vueApp.component('App', AppComponent)
const nuxt = createNuxtApp({ app, ssrContext })
const nuxt = createNuxtApp({ vueApp, ssrContext })
await applyPlugins(nuxt, plugins)
await nuxt.hooks.callHook('app:created', app)
await nuxt.hooks.callHook('app:created', vueApp)
return app
return vueApp
}
}
@ -38,23 +38,23 @@ if (process.client) {
entry = async function initApp () {
const isSSR = Boolean(window.__NUXT__?.serverRendered)
const app = isSSR ? createSSRApp(RootComponent) : createApp(RootComponent)
app.component('App', AppComponent)
const vueApp = isSSR ? createSSRApp(RootComponent) : createApp(RootComponent)
vueApp.component('App', AppComponent)
const nuxt = createNuxtApp({ app })
const nuxt = createNuxtApp({ vueApp })
await applyPlugins(nuxt, plugins)
await nuxt.hooks.callHook('app:created', app)
await nuxt.hooks.callHook('app:beforeMount', app)
await nuxt.hooks.callHook('app:created', vueApp)
await nuxt.hooks.callHook('app:beforeMount', vueApp)
nuxt.hooks.hookOnce('page:finish', () => {
nuxt.isHydrating = false
})
app.mount('#__nuxt')
vueApp.mount('#__nuxt')
await nuxt.hooks.callHook('app:mounted', app)
await nuxt.hooks.callHook('app:mounted', vueApp)
await nextTick()
}

View File

@ -2,7 +2,6 @@
import { getCurrentInstance, reactive, defineAsyncComponent } from 'vue'
import type { App, VNode } from 'vue'
import { createHooks, Hookable } from 'hookable'
import { defineGetter } from './utils'
import { legacyPlugin, LegacyContext } from './legacy'
type NuxtMeta = {
@ -26,7 +25,7 @@ export interface RuntimeNuxtHooks {
}
export interface NuxtApp {
app: App<Element>
vueApp: App<Element>
globalName: string
hooks: Hookable<RuntimeNuxtHooks>
@ -62,13 +61,13 @@ export interface LegacyPlugin {
}
export interface CreateOptions {
app: NuxtApp['app']
vueApp: NuxtApp['vueApp']
ssrContext?: NuxtApp['ssrContext']
globalName?: NuxtApp['globalName']
}
export function createNuxtApp (options: CreateOptions) {
const nuxt: NuxtApp = {
const nuxtApp: NuxtApp = {
provide: undefined,
globalName: 'nuxt',
payload: reactive({
@ -81,55 +80,56 @@ export function createNuxtApp (options: CreateOptions) {
...options
} as any as NuxtApp
nuxt.hooks = createHooks<RuntimeNuxtHooks>()
nuxt.hook = nuxt.hooks.hook
nuxt.callHook = nuxt.hooks.callHook
nuxtApp.hooks = createHooks<RuntimeNuxtHooks>()
nuxtApp.hook = nuxtApp.hooks.hook
nuxtApp.callHook = nuxtApp.hooks.callHook
nuxt.provide = (name: string, value: any) => {
nuxtApp.provide = (name: string, value: any) => {
const $name = '$' + name
defineGetter(nuxt, $name, value)
defineGetter(nuxt.app.config.globalProperties, $name, value)
defineGetter(nuxtApp, $name, value)
defineGetter(nuxtApp.vueApp.config.globalProperties, $name, value)
}
// Inject $nuxt
defineGetter(nuxt.app, '$nuxt', nuxt)
defineGetter(nuxt.app.config.globalProperties, '$nuxt', nuxt)
defineGetter(nuxtApp.vueApp, '$nuxt', nuxtApp)
defineGetter(nuxtApp.vueApp.config.globalProperties, '$nuxt', nuxtApp)
// Expose nuxt to the renderContext
if (nuxt.ssrContext) {
nuxt.ssrContext.nuxt = nuxt
if (nuxtApp.ssrContext) {
nuxtApp.ssrContext.nuxt = nuxtApp
}
// (temporary) Expose NuxtWelcome component in dev
if (process.dev) {
nuxt.app.component('NuxtWelcome', defineAsyncComponent(() => import('./components/nuxt-welcome.vue')))
// @ts-ignore
nuxtApp.vueApp.component('NuxtWelcome', defineAsyncComponent(() => import('./components/nuxt-welcome.vue')))
}
if (process.server) {
// Expose to server renderer to create window.__NUXT__
nuxt.ssrContext = nuxt.ssrContext || {}
nuxt.ssrContext.payload = nuxt.payload
nuxtApp.ssrContext = nuxtApp.ssrContext || {}
nuxtApp.ssrContext.payload = nuxtApp.payload
}
// Expose runtime config
if (process.server) {
nuxt.provide('config', options.ssrContext.runtimeConfig.private)
nuxt.payload.config = options.ssrContext.runtimeConfig.public
nuxtApp.provide('config', options.ssrContext.runtimeConfig.private)
nuxtApp.payload.config = options.ssrContext.runtimeConfig.public
} else {
nuxt.provide('config', reactive(nuxt.payload.config))
nuxtApp.provide('config', reactive(nuxtApp.payload.config))
}
return nuxt
return nuxtApp
}
export function applyPlugin (nuxt: NuxtApp, plugin: Plugin) {
export function applyPlugin (nuxtApp: NuxtApp, plugin: Plugin) {
if (typeof plugin !== 'function') { return }
return callWithNuxt(nuxt, () => plugin(nuxt))
return callWithNuxt(nuxtApp, () => plugin(nuxtApp))
}
export async function applyPlugins (nuxt: NuxtApp, plugins: Plugin[]) {
export async function applyPlugins (nuxtApp: NuxtApp, plugins: Plugin[]) {
for (const plugin of plugins) {
await applyPlugin(nuxt, plugin)
await applyPlugin(nuxtApp, plugin)
}
}
@ -139,7 +139,7 @@ export function normalizePlugins (_plugins: Array<Plugin | LegacyPlugin>) {
const plugins = _plugins.map((plugin) => {
if (isLegacyPlugin(plugin)) {
needsLegacyContext = true
return (nuxt: NuxtApp) => plugin(nuxt._legacyContext!, nuxt.provide)
return (nuxtApp: NuxtApp) => plugin(nuxtApp._legacyContext!, nuxtApp.provide)
}
return plugin
})
@ -198,3 +198,7 @@ export function useNuxtApp (): NuxtApp {
export function useRuntimeConfig (): Record<string, any> {
return useNuxtApp().$config
}
function defineGetter<K extends string | number | symbol, V> (obj: Record<K, V>, key: K, val: V) {
Object.defineProperty(obj, key, { get: () => val })
}

View File

@ -1,14 +1,13 @@
/* eslint-disable no-console */
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(({ app }) => {
export default defineNuxtPlugin((nuxtApp) => {
// Only activate in development
const logs = app.$nuxt.payload.logs || []
const logs = nuxtApp.payload.logs || []
if (logs.length > 0) {
const ssrLogStyle = 'background: #003C3C;border-radius: 0.5em;color: white;font-weight: bold;padding: 2px 0.5em;'
console.groupCollapsed && console.groupCollapsed('%cNuxt Server Logs', ssrLogStyle)
logs.forEach(logObj => (console[logObj.type] || console.log)(...logObj.args))
delete app.$nuxt.payload.logs
delete nuxtApp.payload.logs
console.groupEnd && console.groupEnd()
}
})

View File

@ -1,7 +1,7 @@
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(({ app }) => {
app.mixin({
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.mixin({
beforeCreate () {
const { _registeredComponents } = this.$nuxt.ssrContext
const { __moduleIdentifier } = this.$options

View File

@ -1,8 +1,7 @@
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(({ app }) => {
const { $nuxt } = app
$nuxt.hook('app:mounted', () => {
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('app:mounted', () => {
const el = document.createElement('div')
el.id = 'nuxt-progress'
document.body.appendChild(el)
@ -16,7 +15,7 @@ export default defineNuxtPlugin(({ app }) => {
const progress = 10000 / Math.floor(duration)
let timeout
let interval
$nuxt.hook('page:start', () => {
nuxtApp.hook('page:start', () => {
if (timeout) { return }
timeout = setTimeout(() => {
let width = 10
@ -29,7 +28,7 @@ export default defineNuxtPlugin(({ app }) => {
}, 100)
}, 200)
})
$nuxt.hook('page:finish', () => {
nuxtApp.hook('page:finish', () => {
timeout && clearTimeout(timeout)
timeout = null
interval && clearInterval(interval)

View File

@ -1,3 +0,0 @@
export function defineGetter<K extends string | number | symbol, V> (obj: Record<K, V>, key: K, val: V) {
Object.defineProperty(obj, key, { get: () => val })
}

View File

@ -36,10 +36,10 @@ ${options.components.map((c) => {
}).join(',\n')}
}
export default function (nuxt) {
export default function (nuxtApp) {
for (const name in components) {
nuxt.app.component(name, components[name])
nuxt.app.component('Lazy' + name, components[name])
nuxtApp.vueApp.component(name, components[name])
nuxtApp.vueApp.component('Lazy' + name, components[name])
}
}
`

View File

@ -6,7 +6,7 @@ import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin((nuxt) => {
const manager = createMetaManager(process.server)
nuxt.app.use(manager)
nuxt.vueApp.use(manager)
nuxt._useMeta = (meta: MetaObject) => manager.addMeta(meta)

View File

@ -6,7 +6,7 @@ import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin((nuxt) => {
const head = createHead()
nuxt.app.use(head)
nuxt.vueApp.use(head)
nuxt._useMeta = (meta: MetaObject) => {
const headObj = ref(meta as any)

View File

@ -5,10 +5,10 @@ import { defineNuxtPlugin } from '#app'
// @ts-ignore
import metaConfig from '#build/meta.config.mjs'
export default defineNuxtPlugin((nuxt) => {
export default defineNuxtPlugin((nuxtApp) => {
useMeta(metaConfig.globalMeta)
nuxt.app.mixin({
nuxtApp.vueApp.mixin({
[metaConfig.mixinKey] () {
const instance = getCurrentInstance()
const options = instance?.type || /* nuxt2 */ instance?.proxy?.$options
@ -20,6 +20,6 @@ export default defineNuxtPlugin((nuxt) => {
for (const name in Components) {
// eslint-disable-next-line import/namespace
nuxt.app.component(name, Components[name])
nuxtApp.vueApp.component(name, Components[name])
}
})

View File

@ -17,6 +17,7 @@
import { getCurrentInstance, ref } from 'vue'
import NuxtLayout from './layout'
import { useNuxtApp } from '#app'
export default {
name: 'NuxtPage',
@ -31,17 +32,17 @@ export default {
// Disable HMR reactivity in production
const updatedComponentLayout = process.dev ? ref(null) : null
const { $nuxt } = getCurrentInstance().proxy
const nuxtApp = useNuxtApp()
function onSuspensePending (Component) {
if (process.dev) {
updatedComponentLayout.value = Component.type.layout || null
}
return $nuxt.callHook('page:start', Component)
return nuxtApp.callHook('page:start', Component)
}
function onSuspenseResolved (Component) {
return $nuxt.callHook('page:finish', Component)
return nuxtApp.callHook('page:finish', Component)
}
return {

View File

@ -12,12 +12,10 @@ import { defineNuxtPlugin } from '#app'
// @ts-ignore
import routes from '#build/routes'
export default defineNuxtPlugin((nuxt) => {
const { app } = nuxt
app.component('NuxtPage', NuxtPage)
app.component('NuxtLayout', NuxtLayout)
app.component('NuxtLink', RouterLink)
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.component('NuxtPage', NuxtPage)
nuxtApp.vueApp.component('NuxtLayout', NuxtLayout)
nuxtApp.vueApp.component('NuxtLink', RouterLink)
const routerHistory = process.client
? createWebHistory()
@ -27,31 +25,31 @@ export default defineNuxtPlugin((nuxt) => {
history: routerHistory,
routes
})
app.use(router)
nuxt.provide('router', router)
nuxtApp.vueApp.use(router)
nuxtApp.provide('router', router)
const previousRoute = shallowRef(router.currentRoute.value)
router.afterEach((_to, from) => {
previousRoute.value = from
})
Object.defineProperty(app.config.globalProperties, 'previousRoute', {
Object.defineProperty(nuxtApp.vueApp.config.globalProperties, 'previousRoute', {
get: () => previousRoute.value
})
nuxt.hook('app:created', async () => {
nuxtApp.hook('app:created', async () => {
if (process.server) {
router.push(nuxt.ssrContext.url)
router.push(nuxtApp.ssrContext.url)
}
await router.isReady()
const is404 = router.currentRoute.value.matched.length === 0
if (process.server && is404) {
const error = new Error(`Page not found: ${nuxt.ssrContext.url}`)
const error = new Error(`Page not found: ${nuxtApp.ssrContext.url}`)
// @ts-ignore
error.statusCode = 404
nuxt.ssrContext.error = error
nuxtApp.ssrContext.error = error
}
})
})