'"Uncaught SyntaxError: Cannot use import statement outside a module" When Importing ReactJS
Today I decided to try to learn React, but whenever I try to import the two modules below:
import React from "react"
import ReactDOM from "react-dom"
I get the error:
Uncaught SyntaxError: Cannot use import statement outside a module
Here's the steps I've taken to try to create my React program:
- Install NodeJS
- Add NodeJS to environmental variables
- Create new folder for my program
- Create HTML, CSS, and JS files in my folder
Why am I getting this error, and how can I fix it?
Solution 1:[1]
I assume this is your first time working with React? I see that you have installed NodeJs, which is great!
I recommend that you get started with a complete React app such as Create React App.
Solution 2:[2]
You need to add this to your package.json and it should work. If you are going to use es6 import statements you need to tell node you are using modules inside of your package.json like this.
"type": "module",
Solution 3:[3]
I am also new to react and using visual studio2022 to write the react code in MVC project. I created login page exactly same as https://github.com/narendra315/yt-210911-react-login-page/blob/master/src/LoginComponent2.js and was getting same error as
Uncaught SyntaxError: Cannot use import statement outside a module
fixed it by removing the import as well as export line at the end. I replaced the export line with
ReactDOM.render(<LoginComponent />, document.getElementById('content'));
where LoginComponent is my class and content is id of my Index.cshtml page This fixed my issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Benjamin |
Solution 2 | Jordan |
Solution 3 | A.Muqtadir |