Goby
Goby

Reputation: 57

Trouble importing the "uuid" npm package. TypeError: Relative references must start with either "/", "./", or "../"

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". enter image description here

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

Answers (1)

Igor Morozov
Igor Morozov

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:

  • Setup a static server that will serve uuid. Then, you can import it by its url (e.g import { v4 as uuidv4 } from './uuid';). This is generally not recommended.
  • Use CDN. It's similar to the previous method, but this time someone will set up a static server for you. This is often used in production because of good performance, and you don't need to do anything for this. It's simple: import { v4 as uuidv4 } from 'https://jspm.dev/uuid';
  • But not all libraries are hosted on CDNs. Also, you'd probably need to optimize your dependencies and code. So for complex applications, you should use a so called bundler. Here are a few of the most popular: Vite, Rollup, Webpack, Parcel. What bundlers do: they analyze your imports and then produce a single js file called an "entrypoint". Depending on configuration they can combine all dependencies into one file, or insert special code that will dynamically import your dependencies from other files when they are needed for code to execute.

Upvotes: 1

Related Questions