reactjsastrojsmdxjs

Astro.js + MDX: Unexpected `ExpressionStatement` in code: only import/exports are supported


I'm trying to write a new blog post with MDX within my Astro.js blog, but it keeps throwing Unexpected ExpressionStatement in code: only import/exports are supported any time I include a React-based JSX component. Nothing online speaks of this problem.

Here's a larger trace:

 error   Unexpected `ExpressionStatement` in code: only import/exports are supported
  File:
    /home/username/projects/astro-blog/src/content/blog/test.mdx:2:1
  Code:
    1 | ---
    > 2 | title: "Test"
        | ^

test.mdx

---
title: "Test"
pubDate: "2023-11-30 00:41:27 -0500"
description: "Testing!"
---
import MapChart from "@components/MapChart.tsx";
<MapChart />

It's weird because it makes totally no sense, the error is completely irrelevant to what causes it.

MapChart.tsx (placeholder)

export default function MapChart() {
  return <div>Test Component</div>
}

If the import is removed, the error goes away and is replaced by an undefined component error. But if the component is removed, it doesn't complain. What's going on?


Solution

  • The solution is to add a newline of space between the import and the space lines. It's very dumb, and I only found it after searching the Astro discord.

    Simply go from

    ---
    title: "Test"
    pubDate: "2023-11-30 00:41:27 -0500"
    description: "Testing!"
    ---
    import MapChart from "@components/MapChart.tsx";
    <MapChart />
    

    to

    ---
    title: "Test"
    pubDate: "2023-11-30 00:41:27 -0500"
    description: "Testing!"
    ---
    import MapChart from "@components/MapChart.tsx";
    
    <MapChart />
    

    And the problem will be resolved.