You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack编译React时遇Unexpected token错误,求有效解决方案

Fixing the "Unexpected token" Error in Your React Code

Hey there! Let's break down that frustrating "Unexpected token" error you're running into—this is one of the most common roadblocks when starting out with React, so you're definitely not alone here.

First, let's look at the code snippet you shared:

// index.js
import React from "react"; 
import ReactDOM from "react-dom"; 

const title = 'My React page'; 

ReactDOM.render( 
  <div>{title}</div>, 
  document.getElementBy... // Looks like this line is cut off!
);

The "Unexpected token" error almost always comes down to JSX not being properly transpiled (converted into plain JavaScript that browsers understand). Here are the most likely fixes to try:

  • Make sure you're using Babel to transpile JSX
    React's JSX syntax isn't native to browsers, so you need Babel with the React preset to convert it. If you're setting up your project manually:

    1. Install the required packages:
      npm install @babel/core @babel/preset-react babel-loader --save-dev
      
    2. Create a .babelrc or babel.config.json file in your project root with this config:
      {
        "presets": ["@babel/preset-react"]
      }
      
    3. If you're using Webpack, update your webpack.config.js to process .js/.jsx files with Babel:
      module.exports = {
        module: {
          rules: [
            {
              test: /\.(js|jsx)$/,
              exclude: /node_modules/,
              use: 'babel-loader'
            }
          ]
        }
      };
      
  • Skip manual setup with Create React App
    If you're struggling with manual config, the easiest fix is to use the official Create React App tool, which sets up Babel, Webpack, and all necessary tools automatically:

    npx create-react-app my-react-project
    

    Then move your code into the src/index.js file of the new project—it should work out of the box.

  • Double-check your incomplete code line
    Your snippet cuts off at document.getElementBy...—make sure this is finished as document.getElementById('root') (and that you have a <div id="root"></div> in your index.html file). While this might not be the direct cause of the token error, it will cause another issue once you fix the transpilation.

Give these steps a try—most likely the transpilation setup is missing, which is why the browser is choking on the JSX <div>{title}</div> syntax.

内容的提问来源于stack exchange,提问作者lars915

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:41:01