为什么在我的设置中使用“@babel/preset-env”和“@babel/preset-typescript”需要“@babel/plugin-proposal-optional-chaining”

pip*_*set 5 webpack webpack-4

我有一个使用 Typescript 和 @babel/preset-env 的项目。与 Webpack 捆绑失败并显示此错误和以下配置。

如果我取消注释强制@babel/plugin-proposal-optional-chaining包含的行,则编译有效。如果我将 Safari、Edge 或 IE 11 添加到targets字符串中,它也可以工作。

这是为什么?

ERROR in ./src/bla.ts 58:23
Module parse failed: Unexpected token (58:23)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
>       if (foo?.bar === undefined) {
Run Code Online (Sandbox Code Playgroud)
ERROR in ./src/bla.ts 58:23
Module parse failed: Unexpected token (58:23)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
>       if (foo?.bar === undefined) {
Run Code Online (Sandbox Code Playgroud)

小智 8

Webpack 4 中的 JS 解析器不支持可选链。由于targets:"last 2 Chrome versions, last 2 Firefox versions"代码没有被 babel-loader 转换(因为这些目标支持它),所以 Webpack 无法解析它。targets如您@babel/plugin-proposal-optional-chaining所言,更改与手动包含的效果相同,即 babel-loader 会在 Webpack 阻塞之前转换代码。

相关:https : //github.com/webpack/webpack/issues/10227

根据那个问题,Webpack 5 将使用更新的解析器来解决这个问题。