Home > front end >  Uncaught TypeError: Failed to resolve module specifier "uuid" in Javascript
Uncaught TypeError: Failed to resolve module specifier "uuid" in Javascript

Time:03-27

This is probably a very simple question, but I can't figure it out even after reading many articles. I don't know any Node.js, and I just want to use the uuid generator from here.

When I follow the instruction and put

import { v4 as uuidv4 } from 'uuid';
uuidv4();

The browser tells me "Uncaught TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../"." I'm guessing maybe I need to import some .js file from "node_module", so I opened the node_module and only see a lot of files that I don't understand at all. This is very frustrating, and the same problem may occur when I try to use any other npm modules in the future.

CodePudding user response:

You should first make sure that your imported object is really exported from other source. Refer to this site for general understanding.

import-export-in-js

CodePudding user response:

To import from a pathless package name like you are trying to do, you need some build chain that supports resolving those pathless package names against the node_modules folder for you, and know from what file exactly to do the import in that package, like webpack, rollup, or parcel do.

If you don't want such a build stack, npm loses most of the usefulness for you immediately.

You can however, as you mentioned, try to find the file inside that node_modules/uuid folder. To help with that, look into the package's package.json file and look for "main". That usually tells you what file the imports are being resolved against.

Unfortunately, in this case all the information related to modules is pointing towards a dist folder, which doesn't exist unless you build the module.

To import from source, try this:

import { v4 as uuid4 } from '/node_modules/uuid/src/index.js';
  • Related