Search code examples
reactjsjsxgatsbyprettiermdxjs

Enable auto (self)-closing tags for JSX in MDX file


I am moving a website to Gatsby. For article posts, the original source was written as HTML files. I want to take advantage of using MDX for those content. However, copy-paste tons of articles from HTML to MDX produce much pain. Particularly, MDX parser usually complains about Expected corresponding JSX closing tag for ... I wonder if prettier or any formatter can help with auto adding self-closing tags for MDX files.

Example:

<img
  class="wp-image-1221 size-full"
  src="/assets/images/articles-news/Yasmin_pic_4.png"
  alt=""
  width="504"
  height="377"
>

Expected formatted output

<img
  class="wp-image-1221 size-full"
  src="/assets/images/articles-news/Yasmin_pic_4.png"
  alt=""
  width="504"
  height="377"
/>

// or

<img
  class="wp-image-1221 size-full"
  src="/assets/images/articles-news/Yasmin_pic_4.png"
  alt=""
  width="504"
  height="377"
></img>

Solution

  • The Prettier MDX parser fails at parsing tags that are not self-closing, like the img in your example (playground). However, if you use the HTML parser, Prettier will add the closing / (playground).

    Use the --parser option to format using the HTML parser (note that you need to do it before adding your MDX frontmatter, otherwise the HTML parser won't be able to parse the files either):

    prettier --parser html --write ./my-html-files-from-wordpress
    

    Once the elements are all (self-)closing, you can switch back to using Prettier's inferred parser (MDX for .mdx files):

    prettier --write ./my-formatted-mdx-files