Search code examples
javascripthtmlcssreactjsreact-dom

SyntaxError: Cannot use import statement outside a module in javascript


I'm starting to learn React from zero, locally without set properly all dependencies, the first thing that I did was to use CDNs in my html file, but now I want to know how can I set my machine to import React and ReactDOM and also how can I link CSS to the file.

when I try to run the .js file I got this:

SyntaxError: Cannot use import statement outside a module

When I was using the CDNs links *ReactDOM.render* was working properly

js file

import { React } from 'react'
import { ReactDOM } from 'react-dom'

function FirstComponent(){
    return (<div>
        <Header />
        <Body1 />
        <Footer />    
    </div>)
}

html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="index.js" type="text/babel"></script>
    <link rel="stylesheet" href="./style.css">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
    
</body>
</html>

my point is, how could I run a js file with JSX and ReactDOM.render without using CDNs link in html file


Solution

  • Yo could try to use create-react-app https://create-react-app.dev/

    It will setup your app for you.

    Once your app is setup, you will be able to "build" your app. When you build your app, the React code becomes part of your JavaScript bundle in your application, so you don't need the CDN anymore.