Skip to content

Commit

Permalink
fix: inject color-mode script with nitro plugin (handles mixed spa/ss…
Browse files Browse the repository at this point in the history
…r) (#164)
  • Loading branch information
danielroe authored Sep 22, 2022
1 parent e46d037 commit 620ca17
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 14 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ node_modules
.DS_Store
coverage
dist
.output
21 changes: 11 additions & 10 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions src/runtime/nitro-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { NitroAppPlugin } from 'nitropack'

import { script } from '#color-mode-options'

export default <NitroAppPlugin> function (nitro) {
nitro.hooks.hook('render:html', (htmlContext) => {
htmlContext.head.push(`<script>${script}</script>`)
})
}
5 changes: 1 addition & 4 deletions src/runtime/plugin.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ export default defineNuxtPlugin((nuxtApp) => {
}

if (isVue3) {
useHead({
htmlAttrs,
script: [{ children: script }]
})
useHead({ htmlAttrs })
}

useRouter().afterEach((to) => {
Expand Down

0 comments on commit 620ca17

Please sign in to comment.