Incorrect Babel setup – Unexpected token < in JSX

Loading

This error occurs when your build system isn’t properly configured to handle JSX syntax. Here’s how to resolve it:

Essential Fixes

1. Install Required Babel Packages

npm install --save-dev @babel/preset-react @babel/preset-env

2. Create/Update Babel Configuration

// .babelrc or babel.config.json
{
  "presets": [
    "@babel/preset-env",
    ["@babel/preset-react", {
      "runtime": "automatic" // New JSX transform (React 17+)
    }]
  ]
}

Webpack Configuration

3. Add Babel Loader to Webpack

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.jsx'] // Add .jsx extension
  }
};

Framework-Specific Solutions

4. Create React App (No Configuration Needed)

npx create-react-app my-app --template typescript

5. Next.js Automatic Configuration

// next.config.js
module.exports = {
  reactStrictMode: true,
  compiler: {
    styledComponents: true // If using styled-components
  }
};

Common Mistakes

6. Missing File Extensions

// Wrong (may cause issues)
import MyComponent from './MyComponent';

// Right
import MyComponent from './MyComponent.jsx';

7. Incorrect Script Type in HTML

<!-- index.html -->
<script type="module" src="./index.jsx"></script>

Advanced Configuration

8. Custom Babel Setup for Legacy Projects

// babel.config.js
module.exports = function (api) {
  api.cache(true);
  return {
    presets: [
      ['@babel/preset-env', { targets: { node: 'current' } }],
      '@babel/preset-react'
    ],
    plugins: [
      '@babel/plugin-transform-runtime',
      '@babel/plugin-proposal-class-properties'
    ]
  };
};

9. TypeScript with Babel

npm install --save-dev @babel/preset-typescript
// .babelrc
{
  "presets": [
    "@babel/preset-typescript",
    "@babel/preset-react"
  ]
}

Verification Steps

  1. Create a test JSX file:
// test.jsx
import React from 'react';

function TestComponent() {
  return <div>Test</div>;
}

console.log(TestComponent);
  1. Try building with:
npx babel test.jsx --out-file test-compiled.js

Troubleshooting Checklist

  1. [ ] Verify @babel/preset-react is installed
  2. [ ] Check .babelrc/babel.config.js exists
  3. [ ] Ensure webpack babel-loader is configured
  4. [ ] Confirm file extensions (.jsx) are correct
  5. [ ] Check for conflicting presets/plugins
  6. [ ] Verify React version compatibility
  7. [ ] Test with minimal configuration

Leave a Reply

Your email address will not be published. Required fields are marked *