简体   繁体   English

为什么我的 HTML 文件无法从源模块中找到 javascript function?

[英]Why can't my HTML file find the javascript function from a sourced module?

some_file.js some_file.js

console.log("!")
function hello(){ 
    console.log("Hello!")
}

index.html索引.html

<script src="some_file.js" type="module"></script>
<script>
    hello()
</script>

When hosting and looking at index.html , I recieve a ReferenceError telling me that hello is not found.托管和查看index.html时,我收到一个ReferenceError告诉我找不到hello Following the advice to this thread other similar ones, I've placed something like window.hello = hello in my javascript file to no avail.按照对该线程其他类似的建议,我在我的 javascript 文件中放置了类似window.hello = hello的内容,但无济于事。 I've also attempted exporting the function (which I think I'd only need to do if I were importing it in another javascript file).我还尝试导出 function(我认为只有在将其导入另一个 javascript 文件时才需要这样做)。

Why am I getting a ReferenceError ?为什么我会收到ReferenceError The script is certainly being loaded, because I see the !该脚本肯定正在加载,因为我看到了! print out in the console, but the function isn't being found.在控制台中打印出来,但没有找到 function。

Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules You have to export the function, then within a script tag with type module, import the module you want to use.根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules您必须导出 function,然后在具有类型模块的脚本标签中,导入您要使用的模块。

some_file.js some_file.js

console.log("!")
export function hello(){ 
    console.log("Hello!")
}

index.html索引.html

<script type='module'>
    import {hello} from "./some_file.js" 
    hello()
</script>

Try this:尝试这个:

index.html索引.html

<script src="some_file.js" type="module">
    hello()
</script>

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

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