UglifyJS:使用可选链语法时出错

问题描述

我正在通过 UglifyJS 发送一个脚本,其中包含一些 optional changing syntax 实例。在浏览器中,这种语法完美无缺。但是,UglifyJS 在文件上产生以下错误

Parse error at /Users/username/Developer/script.js:84,32
               node.children[0]?.tagName === "P";
                                ^
ERROR: Unexpected token: punc «.»
    at JS_Parse_Error.get (eval at <anonymous> (/opt/homebrew/lib/node_modules/uglify-js/tools/node.js:18:1),<anonymous>:71:23)
    at fatal (/opt/homebrew/lib/node_modules/uglify-js/bin/uglifyjs:428:27)
    at run (/opt/homebrew/lib/node_modules/uglify-js/bin/uglifyjs:366:9)
    at Object.<anonymous> (/opt/homebrew/lib/node_modules/uglify-js/bin/uglifyjs:275:5)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
    at Module.load (node:internal/modules/cjs/loader:972:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47

我已经搜索了文档,但我不确定要添加哪些参数(如果有)才能使这项工作正常进行。

解决方法

UglifyJS 很可能还不支持可选链操作符 ?.。 我找不到解析器的 source code 中列出的运算符。

该工具的作者建议在 UglifyJS 之前使用 BabelJS 之类的转译器来处理具有异国情调的 JS 语法的文件。

此运算符于 2020 年 6 月刚刚添加到 ECMAScript 标准中(相同的 ?? 运算符,但仅在 18 天前,即 2021 年 2 月 23 日,UglifyJS 才支持它added)。