From: Eduardo San Martin Morote Date: Mon, 2 Aug 2021 17:21:07 +0000 (+0200) Subject: chore: add legacy nuxt plugin X-Git-Tag: v2.0.0-rc.2~12 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=3f277fb9821b43a410030093246184505d022bbc;p=thirdparty%2Fvuejs%2Fpinia.git chore: add legacy nuxt plugin --- diff --git a/nuxt-2/index.js b/nuxt-2/index.js new file mode 100644 index 00000000..2cd5875e --- /dev/null +++ b/nuxt-2/index.js @@ -0,0 +1,27 @@ +import path from 'path' + +/** @type {import('@nuxt/types').Module<{ disableVuex?: boolean}>} */ +export default function NuxtPiniaModule(options) { + const disableStore = 'disableVuex' in options ? options.disableVuex : true + + // Disable default Vuex store (options.features only exists in Nuxt v2.10+) + if (this.options.features && disableStore) { + this.options.features.store = false + } + + this.addPlugin({ + src: path.resolve(__dirname, 'plugin.js'), + fileName: 'pinia.js', + }) + + this.options.build.transpile = this.options.build.transpile || [] + + // transpile pinia if @vue/composition-api is transpiled because we must use the same instance + if ( + !this.options.dev && + !this.options.build.transpile.includes('pinia') && + this.options.build.transpile.includes('@vue/composition-api') + ) { + this.options.build.transpile.push('pinia') + } +} diff --git a/nuxt-2/plugin.js b/nuxt-2/plugin.js new file mode 100644 index 00000000..4f96e787 --- /dev/null +++ b/nuxt-2/plugin.js @@ -0,0 +1,35 @@ +// @ts-check +/// +import Vue from 'vue' +// @ts-expect-error: this must be pinia to load the local module +import { setActivePinia, PiniaPlugin, createPinia } from 'pinia' + +Vue.use(PiniaPlugin) + +/** @type {import('@nuxt/types').Plugin} */ +const myPlugin = (context, inject) => { + // console.log(context) + + /** @type {import('../src').Pinia} */ + const pinia = createPinia() + inject('pinia', pinia) + // simulate the injection ofr `new Vue({ pinia })` + context.app.pinia = pinia + // we also inject it without the $ to be able to use it without it + context.pinia = pinia + setActivePinia(pinia) + + // we bypass warnings + // @ts-expect-error + pinia._p.push(() => ({ $nuxt: context })) + + if (process.server) { + context.beforeNuxtRender(({ nuxtState }) => { + nuxtState.pinia = pinia.state.value + }) + } else if (context.nuxtState && context.nuxtState.pinia) { + pinia.state.value = context.nuxtState.pinia + } +} + +export default myPlugin diff --git a/nuxt-2/types.d.ts b/nuxt-2/types.d.ts new file mode 100644 index 00000000..d663612d --- /dev/null +++ b/nuxt-2/types.d.ts @@ -0,0 +1,17 @@ +import '@nuxt/types' +import 'pinia' +import { Pinia } from 'pinia' +import { Context } from '@nuxt/types' + +declare module '@nuxt/types' { + export interface Context { + pinia: Pinia + $pinia: Pinia + } +} + +declare module 'pinia' { + export interface PiniaCustomProperties { + $nuxt: Context + } +}