首页 > 解决方案 > 使嵌套的 .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.

标签: javascripttypescriptimportmodulereferenceerror

解决方案


推荐阅读