使用导入/导出模块时获取'ReferenceError: not defined'



我已经得到和导出portuserlist .js, importUserList.js和main.js文件。main.js文件包含已经定义的2个变量,我想将其记录到控制台,我还想从main.js文件中记录导入的用户变量。但我一直收到"用户未定义"。我使用了建议的窗口选项,但它没有传递变量。这可以纠正吗?

这是html:

<html lang="en">
<head>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" />
<title></title>
<style>
</style>
<head>
</head>
<body>
<script type="module" src="/importUserList.js"></script>
<script type="text/javascript" src="/main.js"></script>

</body>

这是导出exportUserList.js:

export const user = 'first user'

这是import importUserList.js:

import {user} from './exportList.js'
console.log(user)
window.user = user

,这是main.js:

let names = 'mark'
let numbers = 10
console.log(names)
console.log(numbers)
console.log(user)

选项1:defer您的主脚本,因为模块默认延迟,所以因为您的主脚本没有在模块运行之前运行。

然而,这是一个糟糕的选择,您不应该将其付诸实践,因为这会使您以完全错误的方式使用模块。千万不要那样做。

更好的解决方案是使main.js成为模块,然后告诉它导入运行所需的内容。你不加载模块只绑定他们的数据到globalThis (window在这种情况下),模块的整个点是保持代码包含,所以无论什么需要一个模块的导出,可以根据需要导入。使用模块是为了而不是污染全局作用域=)

因此:删除importUserList.js并将其导入到主脚本中:

import {user} from './exportList.js'
let names = 'mark'
let numbers = 10
console.log(names)
console.log(numbers)
console.log(user)
然后加载你的主脚本作为一个模块:
<script type="module" src="/main.js"></script>

当然要记住模块总是延迟加载的

基本上:如果你正在使用模块,请使用"模块"。

最新更新