我剛開(kāi)始學(xué)習(xí)React。我按照https://react.dev/learn/add-react-to-an-existing-project上的入門(mén)指南進(jìn)行了步驟,但我一直遇到錯(cuò)誤:無(wú)法在模組外部使用import語(yǔ)句。
我做的是:
首先在終端機(jī)中執(zhí)行:
npm init -y npm install React React-dom
然後我創(chuàng)建了一個(gè)index.js文件,並複製了指南中提供的程式碼: `從'react-dom/client'導(dǎo)入{createRoot};
// 清除現(xiàn)有的HTML內(nèi)容 document.body.innerHTML = '';
// 渲染你的React元件 const root = createRoot(document.getElementById('app')); root.render(
但是它沒(méi)有起作用。
幾乎所有的網(wǎng)路解決方案都告訴我在package.json檔案中加入"type": "module
。
我確實(shí)添加了它,但錯(cuò)誤仍然存在。
這是我加入的方式:
{ "name": "project", "devDependency": { "vite": "latest" }, "scripts": { "type": "module", "start": "vite", "dev" : "vite", "build": "vite build", "preview": "vite 預(yù)覽" }, "type": "module", "description": "快速啟動(dòng):", "version": "1.0.0 " , "main": "index.js", "author": "", "license": "ISC", "dependency": { "react": "^18.2.0", "react-dom": " ^ 18.2.0" }, "關(guān)鍵字": [] }
#在script標(biāo)籤內(nèi)部加上"type": "module
也不行:
實(shí)際上,在添加這個(gè)後,React完全崩潰了,因?yàn)樗@示不識(shí)別符號(hào)'<'...
我嘗試過(guò)並且確實(shí)起作用的方法是不實(shí)際下載React,而是插入CDN並使用babel。但是根據(jù)我正在學(xué)習(xí)的免費(fèi)課程,使用CDN不是使用React的好方法。
我完全迷失了。有人能幫忙嗎?
您需要在頂層物件中加入"type": "module",而不是在"scripts"物件中新增。
"scripts"物件中的內(nèi)容可以透過(guò)npm run <x>
來(lái)訪(fǎng)問(wèn),其中<x>
是"scripts"物件中的鍵。
{ "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": [] }