2

I am trying to load the uuid module, which is a project dependency, inside a .html file in a project managed by webpack,

<script type="module">
      import { v4 as uuidv4 } from "uuid";
      window.uuidv4 = uuidv4;

      console.log('uuidv4 ', uuidv4);
 </script>

But this is failing with an error (index):1 Uncaught TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../".

If I try to reference a specific js file relative to the html file, it works properly

<script type="module">
      import myFunc from "./functions/myFunc.js";
      window.uuidv4 = uuidv4;

      console.log('uuidv4 ', uuidv4);
 </script>

Why can't I call the dependency directly in the html, although if I load it directly from myFunc.js it works?

myFunc.js

import { v4 as uuidv4 } from "uuid";
console.log('uuidv4 ', uuidv4); // this works here

export default myFunc() {
   console.log('Hello!');
}
2
  • You'll need to search for solutions to import "bare modules" in HTML files. I'll try to answer when i reach a laptop. Also are you using a bundler right now? Commented Aug 26, 2020 at 12:39
  • Yes I am using webpack Commented Aug 26, 2020 at 12:43

1 Answer 1

2

The reason import { v4 as uuidv4 } from "uuid"; works inside myFunc.js is because it's being bundled by Webpack, and Webpack knows how to resolve modules without "/", "./", or "../" during the bundle time. Eventually all these modules will be in the same file bundle.js (if you haven't customized it).

When you're using the import directly in HTML, the JS code is run directly inside the browser. So the browser doesn't understand how to interpret it. Check out this explanation for more: https://javascript.info/modules-intro#no-bare-modules-allowed

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.