问题描述
我似乎在兜圈子,试图让一个简单的嵌套 .js 文件工作。我从这两个文件开始,它按预期工作:
index.html
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8" />
<script type="module" src="./scripts/file1.js"></script>
<title>Hello World Page</title>
</head>
<body >
<div>
Some prompt: <input id="Xxx" onkeyup="file1Go('index.html calling file1Go()')"/><br />
</div>
</body>
</html>
file1.js
function file1Go(msg) {
alert('In file1.js - ' + msg);
}
然后我创建一个新的 file2.js
并修改 file1.js
以导入它。我还修改了它以导出使用的功能。然后我还修改了 index.html
文件的脚本标签,告诉它 file1.js
现在是这样的模块(以避免“不能在模块外使用导入”错误) :
<script type="module" src="./scripts/file1.js"></script>
修改了file1.js
import { file2Go } from "./file2.js"
export function file1Go(msg) {
alert('In file1.js - ' + msg);
file2Go(msg);
}
新建 file2.js
export function file2Go(msg) {
alert('In file2.js - ' + msg);
}
这导致 html 页面加载和 .js 文件下载都没有错误,但在运行时它无法在 file1.js 中找到导出的函数:
(index):11 Uncaught ReferenceError: file1Go is not defined at HTMLInputElement.onkeyup ((index):11)
就是这样。我做错了什么愚蠢的事情或者我错过了什么? 提前感谢您抽出宝贵时间。
事后思考:将类似的 .js 文件放在一个文件夹中并使用 node.js 执行似乎可行。
更多信息:
我发现以下 <script>
标记确实导入并执行了该函数。我还可以在那里设置 HTML 事件处理程序。只是函数在 <script>
标签的范围之外显然是不可见的,在我的小脑袋看来,这似乎是过度限制和无用的。
<script type="module">
import { file1Go } from "./scripts/file1.js";
file1Go("logging on start in <head> tag..."); // works
document.getElementById('Xxx').onkeyup = file1Go; // also works
</script>
注意:我在这里的最后阶段是使用 TypeScript
,它会有很多文件。为简单起见,我从我的重现中删除了 TypeScript
,并针对我的问题的根本原因。一旦我了解了范围界定问题,我将继续TypeScript
。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)