Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel 7 Unexpected token for React component

I'm upgrading to Babel v7 from v6 and when I build the project I get the following error:

Syntax error: src\app\layout\components\FooterToolbar.js: Unexpected token

Unexpected token <

I'm using the following .babelrc configuration

{
  "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"
  ]
}

And finally this is my webpack config. I put the pollyfills first and then the index.js file in the entry and the babel-loader as transpiler

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' }],
},

Any advice to solve this issue? Thanks a lot

EDIT: I'm using typescript in this project. This is the tsconfig.json

{
    "compilerOptions": {
      "target": "esnext",
      "moduleResolution": "node",
      "esModuleInterop": true,
      "isolatedModules": true,
      "strict": true,
      "noEmit": true,
      "allowJs": true,
      "resolveJsonModule": true,
      "jsx": "react"
    },
    "include": [
      "src"
    ]
  }
like image 534
Miluna Avatar asked Oct 27 '22 16:10

Miluna


1 Answers

Finally got it to work by updating webpack, its plugins and adding the presets and plugins inside the webpack configuration

// 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"
      ]
    }
  }],
},

Thanks for your answers, hopefully this is useful for someone else

like image 135
Miluna Avatar answered Nov 11 '22 17:11

Miluna