davidbonnet / astring

🌳 Tiny and fast JavaScript code generator from an ESTree-compliant AST.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

bug: `import.*` object access causes failure

nerdoza opened this issue · comments

Motivation

It appears that when astring hits an import. object (not a import or import(, but an actual object), it fails with this error: TypeError: Cannot destructure property 'length' of 'code' as it is undefined.

Expected behavior

I believe this import. value should be handled just like any other global value like document. or window., but that's possibly my naive oversimplification.

Actual behavior

TypeError: Cannot destructure property 'length' of 'code' as it is undefined.
    at State.map (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:1166:13)
    at State.writeAndMap (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:1123:10)
    at Object.Literal (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:1057:13)
    at Object.VariableDeclarator (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:530:27)
    at formatVariableDeclaration (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:253:15)
    at Object.VariableDeclaration (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:523:5)
    at Object.ExportNamedDeclaration (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:624:34)
    at Object.Program (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:286:27)
    at generate (file:///home/projects/github-jmjzta/node_modules/astring/dist/astring.mjs:1203:29)
    at Module.toJs (file:///home/projects/github-jmjzta/node_modules/estree-util-to-js/lib/index.js:126:21)

Repo where this is reproduced inside an Astro project: https://stackblitz.com/edit/github-jmjzta?file=astro.config.mjs
To trigger, navigate to the ./test route in the StackBlitz broswer.

commented

import.meta is special. It’s not an object. It doesn’t generally exist.
I recommend reporting to Astro, my hunch is that it’s there. That they are doing replaces on that value and generating an incorrect AST

commented

Also, MDX compiles this fine on the playground: https://mdxjs.com/playground/.
So astring handles this fine with just MDX. Hence my thinking it being Astro.

Thank you @wooorm for the speedy analysis. I suspect you are correct about the import. calls not being replaced as expected.