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

React应用报错:Uncaught SyntaxError: Cannot use import statement outside a module

Fixing "Uncaught SyntaxError: Cannot use import statement outside a module" in React

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 import statements for Node.js modules like react or react-dom from your node_modules folder.
  • JSX syntax (like <h1>hello world</h1>) also needs to be compiled into plain JavaScript before browsers can understand it—something react-scripts handles automatically when you use the official dev server.

Step-by-Step Fixes

  1. Use the React Dev Server (Don’t Open HTML Directly)
    Your package.json already has the correct start script from create-react-app. Run this command in your project directory:

    npm start
    

    This 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.

  2. Check Your Entry File Name
    In your HTML, you’re referencing indexx.js—double-check that this file exists and matches the entry file you’re using. For standard create-react-app setups, the entry file is src/index.js, so you might need to update your script tag to:

    <script src="src/index.js"></script>
    

    Note: When using npm start, react-scripts handles script injection automatically, so you might not even need this line if you follow the official project structure.

  3. Stick to the create-react-app Workflow
    Based on your package.json, you’re using the official React scaffolding—avoid manually tweaking type: "module" or adding custom fields here, since react-scripts already 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:12:32