Unexpected token in @babel/parser during optional chaining transformation
0 reputation · 21 Apr 2023, 18:49 UTC
0 reputation · 21 Apr 2023, 18:49 UTC
When processing modern JavaScript syntax in Babel 7.x, the @babel/parser component throws an "Unexpected token" error if it encounters optional chaining syntax without the appropriate plugin enabled.
While enabling @babel/plugin-proposal-optional-chaining resolves the parsing failure, a configuration uncertainty arises when this is paired with @babel/plugin-proposal-nullish-coalescing. The resulting transpiled code varies based on the sequence in which these plugins are declared in the configuration array.
Because the Babel plugin documentation does not explicitly define the mandatory order for these specific syntax transforms, it is unclear which sequence ensures consistent output across different environment targets.
The order of @babel/plugin-proposal-optional-chaining and @babel/plugin-proposal-nullish-coalescing does not change the logic of the generated AST.
?. for optional chaining and ?? for nullish coalescing..babelrc, babel.config.js or equivalent.@babel/plugin-proposal-optional-chaining before @babel/plugin-proposal-nullish-coalescing (alphabetical order).{
"plugins": [
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing"
]
}
npm list @babel/core @babel/parser @babel/plugin-proposal-optional-chaining @babel/plugin-proposal-nullish-coalescing and note the versions.@babel/plugin-transform-optional-chaining and @babel/plugin-transform-nullish-coalescing.If you are using a Babel version older than 7.9.0, please confirm the exact version so we can advise whether a parser plugin is required.
Use comments to ask for clarification. Post a solution as an answer.
33,630 reputation · 22 Apr 2023, 03:48 UTC
@babel/parser only throws “Unexpected token” for ?. or ?? when the parser plugins optionalChaining and nullishCoalescingOperator are not enabled. In Babel 7.9+ the parser understands these syntaxes natively if you add those parser plugins or use @babel/preset-env, which enables them automatically based on targets. The transform plugins (@babel/plugin-transform-optional-chaining and @babel/plugin-transform-nullish-coalescing) then rewrite the AST; they are independent and can be listed in any order. If you rely on preset-env you do not need to list them manually.