eslint / espree

An Esprima-compatible JavaScript parser
BSD 2-Clause "Simplified" License
2.26k stars 189 forks source link

Error parsing file starting with '#!/usr/bin/env node' #548

Closed DiffYao closed 2 years ago

DiffYao commented 2 years ago

const crossEnv = require('..')

crossEnv(process.argv.slice(2), {shell: true})

- error Msg

SyntaxError: Unexpected character '!' at Espree.raise (/Users/diffyao/Code/node_learn/npm_check/node_modules/espree/dist/espree.cjs:654:25) at Espree.pp.readToken_numberSign (/Users/diffyao/Code/node_learn/npm_check/node_modules/acorn/dist/acorn.js:5050:10) at Espree.pp.getTokenFromCode (/Users/diffyao/Code/node_learn/npm_check/node_modules/acorn/dist/acorn.js:5125:19) at Espree.pp.readToken (/Users/diffyao/Code/node_learn/npm_check/node_modules/acorn/dist/acorn.js:4815:17) at Espree.readToken (/Users/diffyao/Code/node_learn/npm_check/node_modules/acorn-jsx/index.js:469:20) at Espree.pp.nextToken (/Users/diffyao/Code/node_learn/npm_check/node_modules/acorn/dist/acorn.js:4806:17) at Espree.parse (/Users/diffyao/Code/node_learn/npm_check/node_modules/acorn/dist/acorn.js:585:10) at Espree.parse (/Users/diffyao/Code/node_learn/npm_check/node_modules/espree/dist/espree.cjs:564:35) at Object.parse (/Users/diffyao/Code/node_learn/npm_check/node_modules/espree/dist/espree.cjs:869:38) at exports.default (/Users/diffyao/Code/node_learn/npm_check/parser/espree_parser.js:8:20) { index: 1, lineNumber: 1, column: 2 }



As far as I know, acorn supports this feature through `options.allowHashBang (JS API)`.

Does espree support this feature ?
DiffYao commented 2 years ago

Issue is probably that espree is still https://github.com/eslint/espree/issues/283. I think the fix will be to just do what eslint does and replace it with a line comment before handing it to the parser.

btmills commented 2 years ago

Since ESLint already handles this, I don't see us making any changes from the decision in #283. Are you using Espree outside ESLint? If so, three ideas:

  1. Yes, stripping the hashbang beforehand will work for now.
  2. You could use Acorn directly so that option is available. Espree intentionally only passes known options, so the allowHashBang option wouldn't work inside Espree.
  3. You could contact the authors of the hashbang proposal to see if they'll push it to stage 4. Then Espree would likely include built-in support for it based on the ecmaVersion setting.