我有一个项目使用Typescript和@babel/preset-env。 使用Webpack打包时出现以下错误和配置:
如果我取消注释行,强制包括@babel/plugin-proposal-optional-chaining,则编译可以正常工作。 如果我将Safari,Edge或IE 11添加到目标字符串中,它也可以正常工作。
为什么会这样呢?
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",
],
},
},
},
],
},
};