将函数定义为ES6模块,在type=module
内的index.html
中导入的外部JS文件中,由于import/export
只能在模块内使用,然后将其设置在全局Window.prototype
上,以便其可访问第二个script
标记的代码范围,但其不工作。
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>Simple html document.</p>
<script type="module">
import { showPlayerName } from './test.js'
Window.prototype.showPlayerName = showPlayerName;
</script>
<script type="text/javascript">
showPlayerName();
</script>
</body>
</html>
测试.js
export function showPlayerName(){
return 'Leo Messi';
}
Error: index.html: Uncaught ReferenceError: showPlayerName is not defined
如果函数在<script type="module"></script>
内部调用,而<script type="module"></script>
甚至不运行,为什么
有人能让我知道为什么调用内部type=module
和window.showPlayerName
在非type="module"
不会工作。
谢谢
1条答案
按热度按时间xytpbqjk1#
当引擎在HTML中遇到模块脚本得
<script>
标记时,模块脚本不会立即运行:因此,当您尝试从非模块脚本调用
showPlayerName
时,它并没有被定义。虽然有一些方法可以通过等待加载您感兴趣的模块脚本来解决这个问题,但更好的方法是,如果您有任何模块脚本,将 * 所有内容 * 放入模块中,这样就不会有问题了。
这也有不需要创建任何全局变量的优点。