gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:18:15 88 4
gpt4 key购买 nike

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

关于webpack - 为什么我的设置中需要 "@babel/plugin-proposal-optional-chaining"使用 "@babel/preset-env"和 "@babel/preset-typescript",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62541359/

88 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com