React应用报错:Uncaught SyntaxError: Cannot use import statement outside a module
Hey there, let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
You’re trying to directly open your local HTML file in the browser—but that’s not how React apps built with create-react-app are meant to run. Here’s the core issue:
- Browsers treat local HTML files as static resources, so they can’t natively resolve
importstatements for Node.js modules likereactorreact-domfrom yournode_modulesfolder. - JSX syntax (like
<h1>hello world</h1>) also needs to be compiled into plain JavaScript before browsers can understand it—somethingreact-scriptshandles automatically when you use the official dev server.
Step-by-Step Fixes
Use the React Dev Server (Don’t Open HTML Directly)
Yourpackage.jsonalready has the correctstartscript fromcreate-react-app. Run this command in your project directory:npm startThis spins up a local development server (usually at
http://localhost:3000), handles all module bundling and JSX compilation, and automatically opens your app in the browser. You won’t need to manually open the HTML file anymore.Check Your Entry File Name
In your HTML, you’re referencingindexx.js—double-check that this file exists and matches the entry file you’re using. For standardcreate-react-appsetups, the entry file issrc/index.js, so you might need to update your script tag to:<script src="src/index.js"></script>Note: When using
npm start,react-scriptshandles script injection automatically, so you might not even need this line if you follow the official project structure.Stick to the
create-react-appWorkflow
Based on yourpackage.json, you’re using the official React scaffolding—avoid manually tweakingtype: "module"or adding custom fields here, sincereact-scriptsalready configures module handling under the hood.
Quick Verification
After running npm start, check the browser console—you shouldn’t see the SyntaxError anymore, and your "hello world" heading should render correctly at http://localhost:3000.
内容的提问来源于stack exchange,提问作者Sesugh Asa

