如何让 webpack 在没有 babel 的情况下接受可选链接

How to make webpack accept optional chaining without babel

场景:

这样做的好处是更小的捆绑包,并且开发时的周转时间快得多。

现在我们想开始使用 stage 4 optional chaining feature which can be enabled in Chrome using a flag

我试过google这个,我能找到的只是babel has a plugin for this

问题:有什么办法可以让webpack接受这个语法,同时省略babel吗?

这是 webpack 当前报告的内容:

ERROR in ./src/js/components/custom-select.js 245:12
Module parse failed: Unexpected token (245:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|      */
|     focus() {
>         this.input?.focus();
|         return this;
|     }
 @ ./src/js/components/components.js 16:0-49 16:0-49

根据 this similar issue, webpack relies on the parser Acorn and thus presumably needs Acorn to support optional chaining first. Acorn has an open pull request here for optional chaining, but in the meantime, a "solution" suggested by a user in the first issue is to disable parsing on the files you need optional using module.noParse 直到 Acorn 和 webpack 支持该功能。

更新:v7.3.0, and according to this webpack issue comment, it sounds like they don't expect webpack to support it until webpack 5 releases. The progress to webpack 5 can be tracked here 开始,Acorn 现在支持可选链接。

关于@Klaycon 的回答,Acorn released today a new version 支持可选链接。 一旦 Webpack 反映了他们的变化——使用 webpack 的可选链接就不再是问题了。

Webpack 4 单独不支持可选链接,但是,它已经在 Webpack 5 中得到支持,所以如果可能的话,最好的做法是 upgrade to Webpack 5

否则,如果您无法更新到 Webpack 5,则应使用 Babel (@babel/plugin-proposal-optional-chaining) 或 TypeScript 编译器(target 至多 ES2019)进行可选的链接转译。