Skip to content

Commit

Permalink
feat: implement fallbackTitle as separate plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Dec 21, 2023
1 parent 0e82a2b commit eb3bc37
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
11 changes: 11 additions & 0 deletions module/src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ import { installNuxtSiteConfig } from 'nuxt-site-config-kit'
import { version } from '../package.json'

export interface ModuleOptions {
/**
* Will ensure a title is always set by providing a fallback title based on the casing the last slug segment.
*
* @default true
*/
fallbackTitle?: boolean
/**
* Will set up a number of defaults for meta tags and Schema.org, if the modules and config are available.
*
Expand Down Expand Up @@ -95,6 +101,11 @@ export default defineNuxtModule<ModuleOptions>({
src: resolve('./runtime/plugin/defaults'),
})
}
if (config.fallbackTitle) {
addPlugin({
src: resolve('./runtime/plugin/titles'),
})
}

// if user disables certain modules we need to pollyfill the imports
const polyfills: Record<string, string[]> = {
Expand Down
36 changes: 36 additions & 0 deletions module/src/runtime/plugin/titles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { defineNuxtPlugin } from 'nuxt/app'
import type { UseHeadOptions } from '@unhead/vue'
import { withoutTrailingSlash } from 'ufo'
import {
computed,
useHead,
useRoute,
} from '#imports'

function titleCase(s: string) {
return s
.replaceAll('-', ' ')
.replace(/\w\S*/g, w => w.charAt(0).toUpperCase() + w.substr(1).toLowerCase())
}

export default defineNuxtPlugin({
name: 'nuxt-seo:fallback-titles',
setup() {
const route = useRoute()
const title = computed(() => {
if (typeof route.meta?.title === 'string')
return route.meta?.title
// if no title has been set then we should use the last segment of the URL path and title case it
const path = withoutTrailingSlash(route.path || '/')
const lastSegment = path.split('/').pop()
return lastSegment ? titleCase(lastSegment) : null
})

const minimalPriority: UseHeadOptions = {
// give nuxt.config values higher priority
tagPriority: 101,
}

useHead({ title }, minimalPriority)
},
})

0 comments on commit eb3bc37

Please sign in to comment.