【问题标题】:Babel 7 Unexpected token for React componentBabel 7 React 组件的意外令牌
【发布时间】:2019-04-04 18:48:43
【问题描述】:

我正在从 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 放在 entry 中,然后将 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' }],
},

有解决这个问题的建议吗?非常感谢

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

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

【问题讨论】:

  • 请编辑您的问题,以便使用代码文本,而不是图像
  • 请创建最小示例,your configuration 无法重现错误
  • 我看到的唯一问题是你没有关闭<Fragment>标签
  • @deathangel908 它在下面被关闭了。代码在更新前工作

标签: javascript reactjs typescript webpack babeljs


【解决方案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"
      ]
    }
  }],
},

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

【讨论】:

猜你喜欢
  • 2016-07-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 2020-10-16
  • 2016-11-28
  • 1970-01-01
  • 2017-11-07
相关资源
最近更新 更多