简体   繁体   English

在 HTML 文件的脚本 JS 标签中使用 ES6 依赖项

[英]Using ES6 dependency in script JS tag of a HTML file

I am trying to load the uuid module, which is a project dependency, inside a .html file in a project managed by webpack,我正在尝试在 webpack 管理的项目中的 .html 文件中加载uuid模块,这是一个项目依赖项,

<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 "../".但这失败并出现错误(index):1 Uncaught TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../".的类型错误(index):1 Uncaught TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../". (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如果我尝试引用相对于 html 文件的特定js文件,它可以正常工作

<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?为什么我不能直接在 html 中调用依赖项,尽管如果我直接从 myFunc.js 加载它它可以工作?

myFunc.js myFunc.js

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

export default myFunc() {
   console.log('Hello!');
}

The reason import { v4 as uuidv4 } from "uuid";原因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.myFunc.js是因为它被 Webpack 捆绑,并且 Webpack 知道如何在捆绑期间解析没有"/", "./", or "../" /”、“./ "/", "./", or "../"的模块。 Eventually all these modules will be in the same file bundle.js (if you haven't customized it).最终,所有这些模块都将位于同一个文件bundle.js (如果您还没有对其进行自定义)。

When you're using the import directly in HTML, the JS code is run directly inside the browser.当您直接在 HTML 中使用导入时,JS 代码直接在浏览器中运行。 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查看更多解释: https : //javascript.info/modules-intro#no-bare-modules-allowed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM