MDX support in NvChad with treesitter

A forest
Photo by Henry Dixon on Unsplash

This is largely an extension to this blog post with some updates and some changes to specifically make it work in NvChad.

1. Add an mdx filetype

Add to ~/.config/nvim/lua/custom/init.lua:

vim.filetype.add({
  extension = {
    mdx = 'mdx'
  }
})

2. Register markdown as the parser for mdx files

In your ~/.config/nvim/lua/custom/plugins.lua file, add or replace this item in the plugins array:

  {
    "nvim-treesitter/nvim-treesitter",
    opts = overrides.treesitter,
    config = function(_, opts)
      dofile(vim.g.base46_cache .. "syntax")
      require("nvim-treesitter.configs").setup(opts)
      -- tell treesitter to use the markdown parser for mdx files
      vim.treesitter.language.register('markdown', 'mdx')
    end,
  },

3. Add tsx highlighting

Create a file .config/nvim/after/queries/markdown/injections.scm with this content:

; extends
((inline) @injection.content
  (#lua-match? @injection.content "^%s*import")
  (#set! injection.language "typescript"))
((inline) @injection.content
  (#lua-match? @injection.content "^%s*export")
  (#set! injection.language "typescript"))

Again, refer to phelipe’s blog post for how and why this works.

That’s it—you have decent mdx support now.

Want to read more like this?