Skip to content

fix: throw error when using defineOgImage* fns client-side #293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions src/logger.ts

This file was deleted.

13 changes: 8 additions & 5 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import {
defineNuxtModule,
hasNuxtModule,
tryResolveModule,
useLogger,
} from '@nuxt/kit'
import { defu } from 'defu'
import { installNuxtSiteConfig } from 'nuxt-site-config/kit'
Expand All @@ -52,6 +51,7 @@ import {
} from './compatibility'
import { extendTypes, getNuxtModuleOptions, isNuxtGenerate } from './kit'
import { normaliseFontInput } from './pure'
import { logger } from './runtime/logger'
import { checkLocalChrome, checkPlaywrightDependency, downloadFont, isUndefinedOrTruthy } from './util'

export interface ModuleOptions {
Expand Down Expand Up @@ -183,8 +183,7 @@ export default defineNuxtModule<ModuleOptions>({
},
async setup(config, nuxt) {
const { resolve } = createResolver(import.meta.url)
const { name, version } = await readPackageJSON(resolve('../package.json'))
const logger = useLogger(name)
const { version } = await readPackageJSON(resolve('../package.json'))
logger.level = (config.debug || nuxt.options.debug) ? 4 : 3
if (config.enabled === false) {
logger.debug('The module is disabled, skipping setup.')
Expand Down Expand Up @@ -402,14 +401,18 @@ export default defineNuxtModule<ModuleOptions>({
handler: resolve(`${basePath}/image`),
})

nuxt.options.optimization.treeShake.composables.client['nuxt-og-image'] = []
if (!nuxt.options.dev) {
nuxt.options.optimization.treeShake.composables.client['nuxt-og-image'] = []
}
;['defineOgImage', 'defineOgImageComponent', 'defineOgImageScreenshot']
.forEach((name) => {
addImports({
name,
from: resolve(`./runtime/app/composables/${name}`),
})
nuxt.options.optimization.treeShake.composables.client['nuxt-og-image'].push(name)
if (!nuxt.options.dev) {
nuxt.options.optimization.treeShake.composables.client['nuxt-og-image'].push(name)
}
})

// community templates must be copy+pasted!
Expand Down
20 changes: 15 additions & 5 deletions src/runtime/app/composables/defineOgImage.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,32 @@
import type { ActiveHeadEntry } from '@unhead/schema'
import type { DefineOgImageInput, OgImageOptions } from '../../types'
import { useNuxtApp, useRequestEvent, useRoute } from '#imports'
import { defu } from 'defu'
import { appendHeader } from 'h3'
import { createError, useNuxtApp, useRequestEvent, useRoute, useState } from 'nuxt/app'
import { ref } from 'vue'
import { createNitroRouteRuleMatcher } from '../../server/util/kit'
import { getOgImagePath, separateProps, useOgImageRuntimeConfig } from '../../shared'
import { createOgImageMeta, normaliseOptions } from '../utils'

// In non-dev client-side environments this is treeshaken
export function defineOgImage(_options: DefineOgImageInput = {}) {
// string is supported as an easy way to override the generated og image data
const route = useRoute()
const basePath = route.path || '/' // (pages may be disabled)
// we keep track of how this function is used, correct usage is that it should have been called
// server-side before client side, if we're only calling it client-side then it means it's being used incorrectly
const state = import.meta.dev ? useState(`og-image:ssr-exists:${basePath}`, () => false) : ref(false)
// clone to avoid any issues
if (!import.meta.server)
if (import.meta.dev && !import.meta.server) {
// should be tree shaken
if (!state.value) {
throw createError({ message: 'You are using a defineOgImage() function in a client-only context. You must call this function within your root component setup.' })
}
return
}
state.value = true

const nuxtApp = useNuxtApp()
const ogImageInstances = nuxtApp.ssrContext!._ogImageInstances || []
const route = useRoute()
const basePath = route.path || '/' // (pages may be disabled)

// need to check route rules hasn't disabled this
const routeRuleMatcher = createNitroRouteRuleMatcher()
Expand Down
10 changes: 10 additions & 0 deletions src/runtime/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { createConsola } from 'consola'
import { colorize } from 'consola/utils'

export const logger = createConsola({
defaults: {
tag: '@nuxtjs/og-image',
},
})

export const gray = (s: string) => colorize('gray', s)
Loading