I have a project using Typescript and @babel/preset-env. Bundling with Webpack fails with this error and the config below.
If I un-comment the line, which forces @babel/plugin-proposal-optional-chaining
to be included, then compilation works. It also works if I add Safari, Edge or IE 11 to the targets
string.
Why is that?
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",
],
},
},
},
],
},
};
The JS parser in Webpack 4 doesn't support optional chaining. With targets:"last 2 Chrome versions, last 2 Firefox versions"
the code is left untransformed by babel-loader (because those targets support it) so Webpack fails to parse it. Changing targets
as you mentioned has the same effect as manually including @babel/plugin-proposal-optional-chaining
, that is, babel-loader transforms the code before Webpack can choke on it.
related: https://github.com/webpack/webpack/issues/10227
According to that issue, Webpack 5 will use an updated parser that will resolve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With