Converting Prismic Documents to MDX

Hello everyone,

I'm currently working on a project where I'm sourcing content from Prismic.
I would like to convert the Prismic documents to MDX files.

Could anyone provide some guidance or point me to relevant resources? Any help would be greatly appreciated.

Thank you in advance!

Hey Carmelo,

@prismicio/client includes an asHTML() helper function which you can use to customize the markup of a rich text field:

const serializer = {
  em: ({ children }) => `<strong>${children}</strong>`,
}

prismic.asHTML(document.data.example_rich_text, { serializer })

You can use the serializer param to convert your content to Markdown instead of HTML, like so:

  em: ({ children }) => `**${children}**`,
}

Here's an example that our developer experience team created a while ago, which I think covers all Markdown elements:

const serializer = {
  heading1: ({ children }) =>
    `# ${children.join('')}\n\n`,
  heading2: ({ children }) =>
    `## ${children.join('')}\n\n`,
  heading3: ({ children }) =>
    `### ${children.join('')}\n\n`,
  heading4: ({ children }) =>
    `#### ${children.join('')}\n\n`,
  heading5: ({ children }) =>
    `##### ${children.join('')}\n\n`,
  heading6: ({ children }) =>
    `###### ${children.join('')}\n\n`,
  paragraph: ({ children }) =>
    `${children.join('')}\n\n`,
  preformatted: ({ text }) =>
    `\`\`\`\n${text}\n\`\`\`\n\n`,
  strong: ({ children }) =>
    `**${children.join('')}**`,
  em: ({ children }) =>
    `_${children.join('')}_`,
  listItem: ({ children }) =>
    `- ${children.join('')}\n`,
  oListItem: ({ children }) =>
    `1. ${children.join('')}\n`,
  list: ({ children }) =>
    `${children.join('')}\n`,
  oList: ({ children }) =>
    `${children.join('')}\n`,
  image: ({ node }) =>
    node.linkTo
      ? `[![${node.alt}](${node.url})](${node.linkTo.url})\n\n`
      : `![${node.alt}](${node.url})\n\n`,
  embed: ({ node }) =>
    `${node.oembed.html}\n\n`,
  hyperlink: ({ node, children }) =>
    `[${children.join('')}](${prismic.asLink(node.data)})`,
  label: ({ children }) =>
    children.join(''),
  span: ({ text }) =>
    text.replace('\n', '<br/>'),
}

(Please test this before using it in production.)

Sam

1 Like

thank you sam, that might indeed help. thanks for sharing!

1 Like