【发布时间】:2021-11-30 13:37:23
【问题描述】:
我有三个文件,分别是index.html、module.js、main.js、index.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" 属性吗?
【问题讨论】:
-
据我所知,模块不声明全局变量。因此它们不能作为“栏”使用,您需要导入它们或从模块本身使它们成为全局
-
"我可以从 index.js 执行 bar() ..." - 不,一旦文件被声明为模块,它就变成了一个闭包,就好像它是它自己的命名空间。访问其功能的唯一方法是导入它们。
标签: javascript module