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.

  1. 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
// @ts-expect-error
import { defineTransformer } from '@nuxt/content/transformers'

export default defineTransformer({
  name: 'my-transformer',
  extensions: ['.names'],
  parse (_id: string, rawContent: string) {
    return {
      _id,
      body: rawContent.trim().split('\n').map(line => line.trim()).sort()
    }
  }
})
  1. Define simple module to register transformer
my-module.ts
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-expect-error
    nuxt.hook('content:context', (contentContext) => {
      contentContext.transformers.push(resolve('./my-module/my-transformer.ts'))
    })
  }
})
  1. Register your module
nuxt.config.ts
import MyModule from './my-module/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.