用于 React 组件的 Babel 7 Unexpected token

IT技术 javascript reactjs typescript webpack babeljs
2021-05-09 20:25:36

我正在从 v6 升级到 Babel v7,当我构建项目时出现以下错误:

语法错误:src\app\layout\components\FooterToolbar.js: Unexpected token

意外令牌 <

我正在使用以下 .babelrc 配置

{
  "presets": [
    ["@babel/preset-env", { "useBuiltIns": "usage", "debug": true }],
    "@babel/preset-typescript",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-syntax-dynamic-import",
    "@babel/plugin-transform-runtime"
  ]
}

最后这是我的 webpack 配置。我首先将 pollyfills 放在条目中,然后将 index.js 文件放在条目中,并将 babel-loader 作为转译器

entry: ["@babel/polyfill", paths.appIndexJs],
// Process JS with Babel.
{
  test: /\.(js|jsx|mjs|ts|tsx)$/,
  exclude: /node_modules/,
  include: paths.appSrc,
  use: [{ loader: 'babel-loader' }],
},

有什么建议可以解决这个问题吗?非常感谢

编辑:我在这个项目中使用typescript。这是 tsconfig.json

{
    "compilerOptions": {
      "target": "esnext",
      "moduleResolution": "node",
      "esModuleInterop": true,
      "isolatedModules": true,
      "strict": true,
      "noEmit": true,
      "allowJs": true,
      "resolveJsonModule": true,
      "jsx": "react"
    },
    "include": [
      "src"
    ]
  }
1个回答

最后通过更新 webpack、它的插件并在 webpack 配置中添加预设和插件来让它工作

// Process JS with Babel.
{
  test: /\.(js|jsx|mjs|ts|tsx)$/,
  exclude: /node_modules/,
  include: paths.appSrc,
  use: [{
    loader: 'babel-loader',
    options: {
      presets: [
        ["@babel/preset-env", { modules: "commonjs" }],
        "@babel/preset-typescript",
        "@babel/preset-react"
      ],
      plugins: [
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-proposal-object-rest-spread",
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-transform-runtime"
      ]
    }
  }],
},

感谢您的回答,希望这对其他人有用