gatsby-mdx Error

05/12/20191 Min Read — In JavaScript

This blog runs on Gatsby with the Gatsby Starter: Minimal Blog by LekoArts.

I recently upgraded some dependencies and ran into some issues.

The repo switched from @mdx-js/tag to @mdx-js/react. During development, everything worked fine. But you couldn't build static HTML files.

I got errors with mdx-utils: className.match is not a function.

mdx-utils is part of gatsby-mdx.

I found a workaround in this issue: Named capture groups not supported (latest Firefox and < Node 10) #366.
Although it doesn't exactly match my error, the culprit became clear: The file gatsby-mdx/packages/mdx-utils/index.js.

It should look like this:

exports.preToCodeBlock = preProps => {
  if (
    // children is code element
    preProps.children &&
    // code props
    preProps.children.props &&
    // if children is actually a <code>
    preProps.children.props.mdxType === 'code'
  ) {
    // we have a <pre><code> situation
    const {
      children: codeString,
      className = '',
      ...props
    } = preProps.children.props

    const match = className.match(/language-([\0-\uFFFF]*)/)

    return {
      codeString: codeString.trim(),
      className,
      language: match != null ? match[1] : '',
      ...props,
    }
  }
  return undefined
}

I still had an old version in my node-modules from an earlier version of gatsby-mdx. You can see the commit here.

It seems like line 17 did cause the issue:

-  const [, match] = className.match(/language-([\0-\uFFFF]*)/);
+  const match = className.match(/language-([\0-\uFFFF]*)/);

Please note: I can't get this working with Netlify as gatsby-mdx hasn't released the fix as a new version yet. Netlify will install node modules for you and will still use the old mdx-utils and gatsby-mdx npm packages.