Transformers in Nuxt Content allow you to programmatically parse, modify, or analyze your content files as they are processed. They are especially useful for:
You can define a transformer using the defineTransformer helper from @nuxt/content:
import { defineTransformer } from '@nuxt/content'
export default defineTransformer({
name: 'title-suffix',
extensions: ['.md'], // File extensions to apply this transformer to
transform(file) {
// Modify the file object as needed
return {
...file,
title: file.title + ' (suffix)',
}
},
})
name (string): A unique name for your transformer.extensions (string): File extensions this transformer should apply to (e.g., ['.md']).transform (function): The function that receives the file object and returns the modified file.Transformers are registered in your nuxt.config.ts:
export default defineNuxtConfig({
content: {
build: {
transformers: [
'~~/transformers/title-suffix',
'~~/transformers/my-custom-transformer',
],
},
},
})
Transformers can add a __metadata field to the file. This field is not stored in the database but can be used for runtime logic.
import { defineTransformer } from '@nuxt/content'
export default defineTransformer({
name: 'component-metadata',
extensions: ['.md'],
transform(file) {
// Example: Detect if a custom component is used
const usesMyComponent = file.body?.includes('<MyCustomComponent>')
return {
...file,
__metadata: {
components: usesMyComponent ? ['MyCustomComponent'] : [],
},
}
},
})
Note: The __metadata field is only available at runtime and is not persisted in the content database.
interface Transformer {
name: string
extensions: string[]
transform: (file: ContentFile) => ContentFile
}
ContentFile is the object representing the parsed content file, including frontmatter, body, and other fields.Transformers are not limited to modifying existing content—they can also be used to add support for new file formats in Nuxt Content. By defining a transformer with a custom parse method, you can instruct Nuxt Content how to read and process files with new extensions, such as YAML.
Suppose you want to support .yml and .yaml files in your content directory. You can create a transformer that parses YAML frontmatter and body, and registers it for those extensions:
import { defineTransformer } from '@nuxt/content'
export default defineTransformer({
name: 'Yaml',
extensions: ['.yml', '.yaml'],
parse: (file) => {
const { id, body } = file
// parse the body with your favorite yaml parser
const parsed = parseYaml(body)
return {
...parsed,
id,
}
},
})
Register your YAML transformer in your Nuxt config just like any other transformer:
export default defineNuxtConfig({
content: {
build: {
transformers: [
'~~/transformers/yaml',
// ...other transformers
],
},
},
})
This approach allows you to extend Nuxt Content to handle any custom file format you need.