From 856c01ab42391a747e2bf2ba5ad88c78caac2c3a Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 7 Mar 2022 15:08:09 +0000 Subject: [PATCH] feat(bridge): auto-inject based on `provide` key from plugins (#3536) --- packages/bridge/src/runtime/app.ts | 16 ++++++++++++++-- test/fixtures/bridge/plugins/setup.js | 8 ++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/bridge/src/runtime/app.ts b/packages/bridge/src/runtime/app.ts index 61d2fa9f65..5dae2be02f 100644 --- a/packages/bridge/src/runtime/app.ts +++ b/packages/bridge/src/runtime/app.ts @@ -74,8 +74,20 @@ export function callWithNuxt any> (nuxt: NuxtAppCo return p } -export function defineNuxtPlugin (plugin: (nuxtApp: NuxtAppCompat) => void): (ctx: Context) => void { - return ctx => callWithNuxt(ctx.$_nuxtApp, plugin, [ctx.$_nuxtApp]) +interface Plugin { + (nuxt: NuxtAppCompat): Promise | Promise<{ provide?: Record }> | void | { provide?: Record } +} + +export function defineNuxtPlugin (plugin: Plugin): (ctx: Context, inject: (id: string, value: any) => void) => void { + return async (ctx, inject) => { + const result = await callWithNuxt(ctx.$_nuxtApp, plugin, [ctx.$_nuxtApp]) + if (result && result.provide) { + for (const key in result.provide) { + inject(key, result.provide[key]) + } + } + return result + } } export const useNuxtApp = (): NuxtAppCompat => { diff --git a/test/fixtures/bridge/plugins/setup.js b/test/fixtures/bridge/plugins/setup.js index e9370590fe..0d3166d26d 100644 --- a/test/fixtures/bridge/plugins/setup.js +++ b/test/fixtures/bridge/plugins/setup.js @@ -2,10 +2,14 @@ import { onGlobalSetup, ref } from '@nuxtjs/composition-api' import { defineNuxtPlugin } from '#app' -export default defineNuxtPlugin((nuxtApp) => { +export default defineNuxtPlugin(() => { const globalsetup = ref('🚧') onGlobalSetup(() => { globalsetup.value = '✅' }) - nuxtApp.provide('globalsetup', globalsetup) + return { + provide: { + globalsetup + } + } })