I just started learning React. I followed the steps from the getting started guide at https://react.dev/learn/add-react-to-an-existing-project, but I keep getting the error: Cannot use import statement outside a module.
What I did is:
First execute in the terminal:
npm init -y npm install React React-dom
Then I created an index.js file and copied the code provided in the guide: `Import {createRoot} from 'react-dom/client';
// Clear existing HTML content document.body.innerHTML = '';
// Render your React component const root = createRoot(document.getElementById('app')); root.render(
But it didn't work.
Almost all solutions on the internet tell me to add "type": "module
in the package.json file.
I did add it but the error persists.
This is how I added it:
{ "name": "project", "devDependency": { "vite": "latest" }, "scripts": { "type": "module", "start": "vite", "dev" : "vite", "build": "vite build", "preview": "vite preview" }, "type": "module", "description": "Quick Start:", "version": "1.0.0 " , "main": "index.js", "author": "", "license": "ISC", "dependency": { "react": "^18.2.0", "react-dom": " ^ 18.2.0" }, "Keyword": [] }
Adding "type": "module
inside the script tag also doesn't work:
In fact, after adding this, React completely crashed because it showed not recognizing the symbol '<'...
What I tried and did work is to not actually download React, but to plug into the CDN and use babel. But according to the free course I'm taking, using a CDN is not a good way to use React.
I'm completely lost. Can anyone help?
P粉1830770972023-09-21 00:42:02
You need to add "type": "module" in the top-level object, not in the "scripts" object.
The content in the "scripts" object can be accessed by npm run <x>
, where <x>
is the key in the "scripts" object.
{ "name": "project", "type": "module", "devDependencies": { "vite": "latest" }, "scripts": { "start": "vite", "dev": "vite", "build": "vite build", "preview": "vite preview" }, "type": "module", "description": "Quick start:", "version": " 1.0.0", "main": "index.js", "author": "", "license": "ISC", "dependencies": { "react": "^18.2.0", "react-dom ": "^18.2.0" }, "keywords": [] }