javascript - 使嵌套的 .js 模块文件工作的问题
问题描述
我似乎在兜圈子,试图让一个简单的嵌套 .js 文件工作。我从这两个文件开始,它按预期工作:
索引.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>
文件1.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);
}
新文件2.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
从我的 repro 中删除了,并针对我的问题的根本原因。一旦我理解了范围界定问题,我将继续讨论TypeScript
.
解决方案
推荐阅读
- amp-html - 同一页面上的多个 amp-auto-ads
- java - 将值从膨胀的 EditText 添加到 ArrayList
- c - 为什么我的代码不能像我想要的那样工作?以及如何检查日期的有效性?
- python - ModuleNotFoundError:没有名为“vaex.remote”的模块
- python - Python 遍历 2dDarray
- amazon-web-services - 如何将 aws 私有存储桶复制到 Azure 存储
- f# - 如何获得一个简单的 F# 应用程序以使用 Paket 进行编译?
- ruby - Rails:防止删除和销毁活动记录
- mysql - 卸载 Wamp 服务器后无法恢复 MySQL 数据库
- php - PHP header()不发送自定义消息