From 620ca1799f8788bcdd275829ffbb796d346138d7 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Thu, 22 Sep 2022 14:08:40 +0100 Subject: [PATCH] fix: inject color-mode script with nitro plugin (handles mixed spa/ssr) (#164) --- .gitignore | 1 + src/module.ts | 21 +++++++++++---------- src/runtime/nitro-plugin.ts | 9 +++++++++ src/runtime/plugin.server.ts | 5 +---- 4 files changed, 22 insertions(+), 14 deletions(-) create mode 100644 src/runtime/nitro-plugin.ts diff --git a/.gitignore b/.gitignore index 915f6ad5..5eb1e908 100755 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ node_modules .DS_Store coverage dist +.output diff --git a/src/module.ts b/src/module.ts index ef9687f6..bb91ef32 100644 --- a/src/module.ts +++ b/src/module.ts @@ -1,7 +1,7 @@ import { promises as fsp } from 'fs' import { join, resolve } from 'pathe' import template from 'lodash.template' -import { addPlugin, addTemplate, defineNuxtModule, addPluginTemplate, isNuxt2, addComponent, addImports, createResolver } from '@nuxt/kit' +import { addPlugin, addTemplate, defineNuxtModule, isNuxt2, addComponent, addImports, createResolver } from '@nuxt/kit' import { name, version } from '../package.json' @@ -54,15 +54,16 @@ export default defineNuxtModule({ addComponent({ name: options.componentName, filePath: resolve(runtimeDir, 'component.' + (isNuxt2() ? 'vue2' : 'vue3') + '.vue') }) addImports({ name: 'useColorMode', as: 'useColorMode', from: resolve(runtimeDir, 'composables') }) - // Nuxt 3 - SSR false - if (!nuxt.options.ssr) { - addPluginTemplate({ - filename: 'color-mode-script.mjs', - getContents () { - return options.script + '\nexport default () => {}' - } - }) - } + // Nuxt 3 and Bridge - inject script + nuxt.hook('nitro:config', (config) => { + config.externals = config.externals || {} + config.externals.inline = config.externals.inline || [] + config.externals.inline.push(runtimeDir) + config.virtual = config.virtual || {} + config.virtual['#color-mode-options'] = `export const script = ${JSON.stringify(options.script, null, 2)}` + config.plugins = config.plugins || [] + config.plugins.push(resolve(runtimeDir, 'nitro-plugin')) + }) if (!isNuxt2()) { return diff --git a/src/runtime/nitro-plugin.ts b/src/runtime/nitro-plugin.ts new file mode 100644 index 00000000..d592728d --- /dev/null +++ b/src/runtime/nitro-plugin.ts @@ -0,0 +1,9 @@ +import type { NitroAppPlugin } from 'nitropack' + +import { script } from '#color-mode-options' + +export default function (nitro) { + nitro.hooks.hook('render:html', (htmlContext) => { + htmlContext.head.push(``) + }) +} diff --git a/src/runtime/plugin.server.ts b/src/runtime/plugin.server.ts index f5a60ee3..95bdda6c 100644 --- a/src/runtime/plugin.server.ts +++ b/src/runtime/plugin.server.ts @@ -43,10 +43,7 @@ export default defineNuxtPlugin((nuxtApp) => { } if (isVue3) { - useHead({ - htmlAttrs, - script: [{ children: script }] - }) + useHead({ htmlAttrs }) } useRouter().afterEach((to) => {