Reputation: 57
I am trying to import a module called "uuid" to my index.js
script which I installed through this command: npm install uuid
.
First I tried using CommonJS syntax, but that gave me this error: Uncaught ReferenceError: require is not defined
const { v4: uuidv4 } = require('uuid');
// ReferenceError: require is not defined
My IDE recommended that I convert my file to an ES module instead:
import { v4 as uuidv4 } from 'uuid';
// SyntaxError: Cannot use import statement outside a module
By adding type="module"
to my index.js
script in the html only produces new errors:
TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../".
I have searched for a while now but can't find anything. Upon trying to follow the error message instructions I try to generate a more direct path to the "uuid" module like this:
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)
Even with this direct path it can't find the module which is weird as it is at least recognizing something when only specifying the module name "uuid".
If it's to any help here is my package.json
dependencies
"dependencies": {
"express": "^4.18.1",
"nodemon": "^2.0.20",
"socket.io": "^4.5.2",
"socket.io-client": "^4.5.4",
"uuid": "^9.0.0"
}
Upvotes: 0
Views: 490
Reputation: 324
You're trying to import uuid
module from node_modules
in the script running in the browser. Unfortunately, it's that simple. The node_modules
work for Node.js only, browsers don't know about them.
There are multiple ways you can fix this:
uuid
. Then, you can import it by its url (e.g import { v4 as uuidv4 } from './uuid';
). This is generally not recommended.import { v4 as uuidv4 } from 'https://jspm.dev/uuid';
Upvotes: 1