如何从 javascript type=module 访问函数

How to access function from a javascript type=module

我有三个文件,分别是index.htmlmodule.jsmain.jsindex.js

INDEX.HTML

....
<body
    <script type="module "src="main.js"></script>
    <script src="index.js"></script>
</body>
...

MODULE.JS

....
function foo(text){
  alert(text)
}

export default foo;
...

MAIN.JS

import foo from "./module.js"
function bar(text){
   foo("FOOBAR")
}

INDEX.JS

bar() // not "type="module"

我可以从 index.js 执行 bar() 而无需在 html 中提供属性 type="module" 吗?

这不可能。正如 Ruben 在评论中提到的,您需要将 main.js 导入 index.js 才能访问其 bar() 函数,否则您将获得

Uncaught ReferenceError: bar is not defined

错误

检查这些问题可能会有帮助: