Webpack编译React时遇Unexpected token错误,求有效解决方案
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:- Install the required packages:
npm install @babel/core @babel/preset-react babel-loader --save-dev - Create a
.babelrcorbabel.config.jsonfile in your project root with this config:{ "presets": ["@babel/preset-react"] } - If you're using Webpack, update your
webpack.config.jsto process.js/.jsxfiles with Babel:module.exports = { module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: 'babel-loader' } ] } };
- Install the required packages:
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-projectThen move your code into the
src/index.jsfile of the new project—it should work out of the box.Double-check your incomplete code line
Your snippet cuts off atdocument.getElementBy...—make sure this is finished asdocument.getElementById('root')(and that you have a<div id="root"></div>in yourindex.htmlfile). 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

