[英]Trouble importing the "uuid" npm package. TypeError: Relative references must start with either "/", "./", or "../"
我正在嘗試將一個名為“uuid”的模塊導入我通過以下命令安裝的index.js
腳本: npm install uuid
。
首先我嘗試使用 CommonJS 語法,但這給了我這個錯誤: Uncaught ReferenceError: require is not defined
const { v4: uuidv4 } = require('uuid');
// ReferenceError: require is not defined
我的 IDE 建議我將文件轉換為 ES 模塊:
import { v4 as uuidv4 } from 'uuid';
// SyntaxError: Cannot use import statement outside a module
通過將type="module"
添加到我在 html 中的index.js
腳本只會產生新的錯誤:
TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../".
我已經搜索了一段時間,但找不到任何東西。 在嘗試按照錯誤消息說明進行操作時,我嘗試生成一個更直接的“uuid”模塊路徑,如下所示:
import { v4 as uuidv4 } from '../node_modules/uuid/dist/v4';
// GET http://localhost:3000/node_modules/uuid/dist/v4 net::ERR_ABORTED 404 (Not Found)
即使使用這個直接路徑,它也找不到奇怪的模塊,因為它至少在僅指定模塊名稱“uuid”時識別出一些東西。
如果對這里有任何幫助,這是我的package.json
依賴項
"dependencies": {
"express": "^4.18.1",
"nodemon": "^2.0.20",
"socket.io": "^4.5.2",
"socket.io-client": "^4.5.4",
"uuid": "^9.0.0"
}
您正在嘗試從瀏覽器中運行的腳本中的node_modules
導入uuid
模塊。 不幸的是,就是這么簡單。 node_modules
僅適用於 Node.js,瀏覽器不知道它們。 有多種方法可以解決此問題:
uuid
的 static 服務器。 然后,您可以通過其 url 導入它(例如import { v4 as uuidv4 } from './uuid';
)。 一般不推薦這樣做。import { v4 as uuidv4 } from 'https://jspm.dev/uuid';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.