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' import { setNuxtAppInstance } from '#app'
export default (ctx, inject) => { export default (ctx, inject) => {
const nuxt = { const nuxtApp = {
app: { vueApp: {
component: Vue.component.bind(Vue), component: Vue.component.bind(Vue),
config: { config: {
globalProperties: {} globalProperties: {}
@ -23,26 +23,26 @@ export default (ctx, inject) => {
globalName: 'nuxt', globalName: 'nuxt',
payload: process.client ? ctx.nuxtState : ctx.ssrContext.nuxt, payload: process.client ? ctx.nuxtState : ctx.ssrContext.nuxt,
isHydrating: ctx.isHMR, isHydrating: ctx.isHMR,
legacyNuxt: ctx.app nuxt2Context: ctx
} }
nuxt.hooks = createHooks() nuxtApp.hooks = createHooks()
nuxt.hook = nuxt.hooks.hook nuxtApp.hook = nuxtApp.hooks.hook
nuxt.callHook = nuxt.hooks.callHook nuxtApp.callHook = nuxtApp.hooks.callHook
if (!Array.isArray(ctx.app.created)) { if (!Array.isArray(ctx.app.created)) {
ctx.app.created = [ctx.app.created] ctx.app.created = [ctx.app.created]
} }
if (process.server) { if (process.server) {
nuxt.ssrContext = ctx.ssrContext nuxtApp.ssrContext = ctx.ssrContext
} }
ctx.app.created.push(function () { 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 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 { export interface NuxtAppCompat {
legacyNuxt: Vue nuxt2Context: Vue
legacyApp: ComponentOptions<Vue> vue2App: ComponentOptions<Vue>
vueApp: VueAppCompat
globalName: string globalName: string

View File

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

View File

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

View File

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

View File

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

View File

@ -2,7 +2,6 @@
import { getCurrentInstance, reactive, defineAsyncComponent } from 'vue' import { getCurrentInstance, reactive, defineAsyncComponent } from 'vue'
import type { App, VNode } from 'vue' import type { App, VNode } from 'vue'
import { createHooks, Hookable } from 'hookable' import { createHooks, Hookable } from 'hookable'
import { defineGetter } from './utils'
import { legacyPlugin, LegacyContext } from './legacy' import { legacyPlugin, LegacyContext } from './legacy'
type NuxtMeta = { type NuxtMeta = {
@ -26,7 +25,7 @@ export interface RuntimeNuxtHooks {
} }
export interface NuxtApp { export interface NuxtApp {
app: App<Element> vueApp: App<Element>
globalName: string globalName: string
hooks: Hookable<RuntimeNuxtHooks> hooks: Hookable<RuntimeNuxtHooks>
@ -62,13 +61,13 @@ export interface LegacyPlugin {
} }
export interface CreateOptions { export interface CreateOptions {
app: NuxtApp['app'] vueApp: NuxtApp['vueApp']
ssrContext?: NuxtApp['ssrContext'] ssrContext?: NuxtApp['ssrContext']
globalName?: NuxtApp['globalName'] globalName?: NuxtApp['globalName']
} }
export function createNuxtApp (options: CreateOptions) { export function createNuxtApp (options: CreateOptions) {
const nuxt: NuxtApp = { const nuxtApp: NuxtApp = {
provide: undefined, provide: undefined,
globalName: 'nuxt', globalName: 'nuxt',
payload: reactive({ payload: reactive({
@ -81,55 +80,56 @@ export function createNuxtApp (options: CreateOptions) {
...options ...options
} as any as NuxtApp } as any as NuxtApp
nuxt.hooks = createHooks<RuntimeNuxtHooks>() nuxtApp.hooks = createHooks<RuntimeNuxtHooks>()
nuxt.hook = nuxt.hooks.hook nuxtApp.hook = nuxtApp.hooks.hook
nuxt.callHook = nuxt.hooks.callHook nuxtApp.callHook = nuxtApp.hooks.callHook
nuxt.provide = (name: string, value: any) => { nuxtApp.provide = (name: string, value: any) => {
const $name = '$' + name const $name = '$' + name
defineGetter(nuxt, $name, value) defineGetter(nuxtApp, $name, value)
defineGetter(nuxt.app.config.globalProperties, $name, value) defineGetter(nuxtApp.vueApp.config.globalProperties, $name, value)
} }
// Inject $nuxt // Inject $nuxt
defineGetter(nuxt.app, '$nuxt', nuxt) defineGetter(nuxtApp.vueApp, '$nuxt', nuxtApp)
defineGetter(nuxt.app.config.globalProperties, '$nuxt', nuxt) defineGetter(nuxtApp.vueApp.config.globalProperties, '$nuxt', nuxtApp)
// Expose nuxt to the renderContext // Expose nuxt to the renderContext
if (nuxt.ssrContext) { if (nuxtApp.ssrContext) {
nuxt.ssrContext.nuxt = nuxt nuxtApp.ssrContext.nuxt = nuxtApp
} }
// (temporary) Expose NuxtWelcome component in dev // (temporary) Expose NuxtWelcome component in dev
if (process.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) { if (process.server) {
// Expose to server renderer to create window.__NUXT__ // Expose to server renderer to create window.__NUXT__
nuxt.ssrContext = nuxt.ssrContext || {} nuxtApp.ssrContext = nuxtApp.ssrContext || {}
nuxt.ssrContext.payload = nuxt.payload nuxtApp.ssrContext.payload = nuxtApp.payload
} }
// Expose runtime config // Expose runtime config
if (process.server) { if (process.server) {
nuxt.provide('config', options.ssrContext.runtimeConfig.private) nuxtApp.provide('config', options.ssrContext.runtimeConfig.private)
nuxt.payload.config = options.ssrContext.runtimeConfig.public nuxtApp.payload.config = options.ssrContext.runtimeConfig.public
} else { } 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 } 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) { 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) => { const plugins = _plugins.map((plugin) => {
if (isLegacyPlugin(plugin)) { if (isLegacyPlugin(plugin)) {
needsLegacyContext = true needsLegacyContext = true
return (nuxt: NuxtApp) => plugin(nuxt._legacyContext!, nuxt.provide) return (nuxtApp: NuxtApp) => plugin(nuxtApp._legacyContext!, nuxtApp.provide)
} }
return plugin return plugin
}) })
@ -198,3 +198,7 @@ export function useNuxtApp (): NuxtApp {
export function useRuntimeConfig (): Record<string, any> { export function useRuntimeConfig (): Record<string, any> {
return useNuxtApp().$config 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' import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(({ app }) => { export default defineNuxtPlugin((nuxtApp) => {
// Only activate in development // Only activate in development
const logs = app.$nuxt.payload.logs || [] const logs = nuxtApp.payload.logs || []
if (logs.length > 0) { if (logs.length > 0) {
const ssrLogStyle = 'background: #003C3C;border-radius: 0.5em;color: white;font-weight: bold;padding: 2px 0.5em;' 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) console.groupCollapsed && console.groupCollapsed('%cNuxt Server Logs', ssrLogStyle)
logs.forEach(logObj => (console[logObj.type] || console.log)(...logObj.args)) logs.forEach(logObj => (console[logObj.type] || console.log)(...logObj.args))
delete app.$nuxt.payload.logs delete nuxtApp.payload.logs
console.groupEnd && console.groupEnd() console.groupEnd && console.groupEnd()
} }
}) })

View File

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

View File

@ -1,8 +1,7 @@
import { defineNuxtPlugin } from '#app' import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(({ app }) => { export default defineNuxtPlugin((nuxtApp) => {
const { $nuxt } = app nuxtApp.hook('app:mounted', () => {
$nuxt.hook('app:mounted', () => {
const el = document.createElement('div') const el = document.createElement('div')
el.id = 'nuxt-progress' el.id = 'nuxt-progress'
document.body.appendChild(el) document.body.appendChild(el)
@ -16,7 +15,7 @@ export default defineNuxtPlugin(({ app }) => {
const progress = 10000 / Math.floor(duration) const progress = 10000 / Math.floor(duration)
let timeout let timeout
let interval let interval
$nuxt.hook('page:start', () => { nuxtApp.hook('page:start', () => {
if (timeout) { return } if (timeout) { return }
timeout = setTimeout(() => { timeout = setTimeout(() => {
let width = 10 let width = 10
@ -29,7 +28,7 @@ export default defineNuxtPlugin(({ app }) => {
}, 100) }, 100)
}, 200) }, 200)
}) })
$nuxt.hook('page:finish', () => { nuxtApp.hook('page:finish', () => {
timeout && clearTimeout(timeout) timeout && clearTimeout(timeout)
timeout = null timeout = null
interval && clearInterval(interval) 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')} }).join(',\n')}
} }
export default function (nuxt) { export default function (nuxtApp) {
for (const name in components) { for (const name in components) {
nuxt.app.component(name, components[name]) nuxtApp.vueApp.component(name, components[name])
nuxt.app.component('Lazy' + name, components[name]) nuxtApp.vueApp.component('Lazy' + name, components[name])
} }
} }
` `

View File

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

View File

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

View File

@ -5,10 +5,10 @@ import { defineNuxtPlugin } from '#app'
// @ts-ignore // @ts-ignore
import metaConfig from '#build/meta.config.mjs' import metaConfig from '#build/meta.config.mjs'
export default defineNuxtPlugin((nuxt) => { export default defineNuxtPlugin((nuxtApp) => {
useMeta(metaConfig.globalMeta) useMeta(metaConfig.globalMeta)
nuxt.app.mixin({ nuxtApp.vueApp.mixin({
[metaConfig.mixinKey] () { [metaConfig.mixinKey] () {
const instance = getCurrentInstance() const instance = getCurrentInstance()
const options = instance?.type || /* nuxt2 */ instance?.proxy?.$options const options = instance?.type || /* nuxt2 */ instance?.proxy?.$options
@ -20,6 +20,6 @@ export default defineNuxtPlugin((nuxt) => {
for (const name in Components) { for (const name in Components) {
// eslint-disable-next-line import/namespace // 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 { getCurrentInstance, ref } from 'vue'
import NuxtLayout from './layout' import NuxtLayout from './layout'
import { useNuxtApp } from '#app'
export default { export default {
name: 'NuxtPage', name: 'NuxtPage',
@ -31,17 +32,17 @@ export default {
// Disable HMR reactivity in production // Disable HMR reactivity in production
const updatedComponentLayout = process.dev ? ref(null) : null const updatedComponentLayout = process.dev ? ref(null) : null
const { $nuxt } = getCurrentInstance().proxy const nuxtApp = useNuxtApp()
function onSuspensePending (Component) { function onSuspensePending (Component) {
if (process.dev) { if (process.dev) {
updatedComponentLayout.value = Component.type.layout || null updatedComponentLayout.value = Component.type.layout || null
} }
return $nuxt.callHook('page:start', Component) return nuxtApp.callHook('page:start', Component)
} }
function onSuspenseResolved (Component) { function onSuspenseResolved (Component) {
return $nuxt.callHook('page:finish', Component) return nuxtApp.callHook('page:finish', Component)
} }
return { return {

View File

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