wooorm / xdm

Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
http://wooorm.com/xdm/
MIT License
595 stars 18 forks source link

Could not parse expression with acorn: Unexpected token #77

Closed chenxsan closed 3 years ago

chenxsan commented 3 years ago

Initial checklist

Latest xdm.

Steps to reproduce

  1. open https://stackblitz.com/edit/node-krxxhd?file=index.js
  2. run node index.js

It seems the return is the culprit.

Expected behavior

No error to happen.

Actual behavior

Using markdown content like - async () => {return;} would throw an error.

Error: Could not parse expression with acorn: Unexpected token
    at async ModuleJob.run (https://node-krxxhd.jw.staticblitz.com/blitz.f91df8ee833f18bedf806af681eeaccd3addac72.js:6:702354)
    at async Loader.import (https://node-krxxhd.jw.staticblitz.com/blitz.f91df8ee833f18bedf806af681eeaccd3addac72.js:6:995064)
    at async Object.r.loadESM (https://node-krxxhd.jw.staticblitz.com/blitz.f91df8ee833f18bedf806af681eeaccd3addac72.js:6:278979) {
  name: '1:16',
  reason: 'Could not parse expression with acorn: Unexpected token',
  line: 1,
  column: 16,
  source: 'micromark-extension-mdx-expression',
  ruleId: 'acorn',
  position: {
    start: { line: 1, column: 16, offset: 15 },
    end: { line: null, column: null }
  }
}

Removing return would fix it.

wooorm commented 3 years ago

Hey!

This is one of the (documented) caveats: { starts an expression in xdm (and mdx-js/mdx@next). The reason is that expressions are powerful: you can have code in your MDX:

The sum of 1 + 1 = {1 + 1}

And it would evaluate to 2.

The code inside braces is actually being parsed. In this case as an expression. So the return fails fatally.

I recommend putting code inside backticks (- `async () => {return;}`). Alternatively, escape the opening brace like so: - async () => \{return;}

wooorm commented 3 years ago

Btw, in v1.5.0, a format option was added. If the input isn’t MDX but just plain markdown, you can also run that through the same process: https://github.com/wooorm/xdm#optionsformat.