为什么我需要使用 "@babel/preset-env" 和 "@babel/preset-typescript" 在设置中进行"@babel/plugin-proposal-optional-cha



我有一个使用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) {
// webpack.config
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: [path.join(__dirname, "src", "index.ts")],
output: {
filename: "[name].js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
title: "Test",
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
}),
],
resolve: {
extensions: [".ts", ".js"],
alias: {
lib: path.join(__dirname, "src", "lib"),
},
},
module: {
rules: [
{
test: /.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
esModule: true,
},
},
"css-loader",
],
},
{
test: /.(woff|woff2|eot|ttf|otf)$/,
use: ["file-loader"],
},
{
test: /.(ts|js)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
[
"@babel/preset-env",
{
modules: false,
corejs: 3,
useBuiltIns: "usage",
include: [
// "@babel/plugin-proposal-optional-chaining", // parsing fails on optional operator without this
],
targets: "last 2 Chrome versions, last 2 Firefox versions",
},
],
"@babel/preset-typescript",
],
},
},
},
],
},
};

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 将使用更新的解析器来解决这个问题。

最新更新