TyrealHu / acorn-typescript

Alternative, TypeScript parser
https://www.npmjs.com/package/acorn-typescript?activeTab=readme
MIT License
145 stars 18 forks source link

Parser fails when used in a ESM context #6

Closed gtm-nayan closed 1 year ago

gtm-nayan commented 1 year ago

It fails to parse something like 1 as number because the plugin does reference equality checks on token types.

But if using it from an ESM file, the users will load acorn/index.mjs, whereas this plugin will load the tokenTypes from acorn/index.js, which means the token types will be different objects even if they are the same token type and the reference equality will return false.

Possible solutions:

  1. Replace tokType reference equality checks with comparing tokType.label
  2. Rename the index.esm.js file to index.mjs and let users import from it manually
  3. Use exports map instead of module since node doesn't care about module and will always load the CJS version of this package (https://publint.dev/acorn-typescript@1.2.5)
TyrealHu commented 1 year ago

Could u show me the case which fails to parse something like 1 as number

gtm-nayan commented 1 year ago
// index.js
import * as acorn from 'acorn';
import { tsPlugin } from 'acorn-typescript';

const source = `1 as number`;
const node = acorn.Parser.extend(tsPlugin()).parse(source, {
    sourceType: 'module',
    ecmaVersion: 'latest',
    locations: true
});

console.log(node);

package.json

{"type": "module"}

will fail with SyntaxError: Unexpected token (1:5)

gtm-nayan commented 1 year ago

I narrowed it down to this line, https://github.com/TyrealHu/acorn-typescript/blob/b01075d466889e6cdbf6d7ee39d20fba12f121f0/src/index.ts#L1904

it returns true when I'm running the tests inside this repo but it's false in my actual project.

TyrealHu commented 1 year ago

This issue has been fixed in version 1.2.7

gtm-nayan commented 1 year ago

Thanks for the quick fix.