简体   繁体   中英

Uncaught SyntaxError: Cannot use import statement outside a module for React

I have the following code that I am trying to run as part of learning React.

HTML

<html>
    <head>
        <link href="index.css" rel="stylesheet">
    </head>
    <body>
        <div id="root">
        </div>
    <script src="index.js"></script>
    </body>
</html>

Javascript

import React from "react"
import ReactDOM from "react-dom"

const navbar= (
    <nav>
        <h1>Alchamentry</h1>
        <ul>
            <li>Pricing</li>
            <li>About</li>
            <li>Contact</li>
        </ul>
    </nav>
)
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(navbar)

package.json

{
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  }
}

Now when I open the browser, I get the following error:

index.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)

and nothing is displayed on the browser. How to fix this? I tried to add the module to the script tag, but it is giving another error that says

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

index.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)

here is how to create a react component. note: a react component must has capitalized name.

 const Navbar = () => { return ( <nav> <h1>Hello, i am NavBar. Nice to meet you. And here are my links</h1> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Profile</a></li> </ul> </nav> ) } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<Navbar/>);
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

You need tools like Webpack and Babel to bundle and transpile jsx to valid JavaScript code. Such tools come out of the box if you try to create a project with packages like CRA.

This jsx isn't valid JavaScript and is not understood by browser's JavaScript engine.

    const navbar= (
    <nav>
        <h1>Alchamentry</h1>
        <ul>
            <li>Pricing</li>
            <li>About</li>
            <li>Contact</li>
        </ul>
    </nav>
)

But if you still want to do all the configs by yourself, you can check this article:

Click

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM