recipes
Transformers
Transformers are responsible for parsing and manipulating contents in Nuxt Content.
Nuxt Content has specific transformers for each content type to parse the raw content and prepare it for querying and rendering.
You can create custom transformers to support new content types or improve functionalities of supported content types.
- Create your transformer. A transformer consists of 4 parts:
name
: Transformer name.extensions
: List of valid file extensions.parse
: If provided, this function will be used to parse the raw content.transform
: Receives that parsed content and manipulates it.
my-transformer.ts
// filename: my-transformer.ts
import { defineTransformer } from '@nuxt/content/transformers'
export default defineTransformer({
name: 'my-transformer',
extensions: ['.names'],
parse (_id, rawContent) {
return {
_id,
body: rawContent.trim().split('\n').map(line => line.trim()).sort()
}
}
})
- Define simple module to register transformer
my-module.mjs
// filename: my-module.mjs
import { resolve } from 'path'
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (_options, nuxt) {
nuxt.options.nitro.externals = nuxt.options.nitro.externals || {}
nuxt.options.nitro.externals.inline = nuxt.options.nitro.externals.inline || []
nuxt.options.nitro.externals.inline.push(resolve('./my-module'))
// @ts-ignore
nuxt.hook('content:context', (contentContext) => {
contentContext.transformers.push(resolve('./my-module/my-transformer.ts'))
})
}
})
- Register your module
nuxt.config.ts
// filename: my-module.mjs
import { resolve } from 'path'
import { defineNuxtConfig } from '@nuxt/kit'
import MyModule from './my-module'
export default defineNuxtConfig({
modules: [
// always put it before @nuxt/content because the transformers
// needs to be loaded before transformation occurs
MyModule,
'@nuxt/content'
]
})
That's it. You can create .names
files in content directory. Checkout transformer example.