如何通过type = module使用脚本中的代码 [英] How to use code from script with type=module
问题描述
我不明白为什么这个琐碎的代码不起作用:
I can't figure out why this trivial code is not working:
index.html:
<!doctype HTML>
<html>
<head>
<script type="module" src="/showImport.js"></script>
</head>
<body>
<button onclick="showImportedMessage();">Show Message</button>
</body>
</html>
showImport.js:
import showMessage from '/show.js';
function showImportedMessage() {
showMessage();
}
show.js:
export default "Why do I need this?";
export function showMessage() {
alert("Hello!");
}
由NPM http服务器提供.当我连接Chrome(v65)时,看到以下错误
It is being served by NPM http-server. When I connect with Chrome (v65), I see the following error
(index):8 Uncaught ReferenceError: showImportedMessage is not defined
at HTMLButtonElement.onclick ((index):8)
onclick @ (index):8
如果我摆脱了type=module
(并通过将showMessage
函数放在showImport.js
中进行导入/导出),一切正常,但是整个目的是使用模块.
If I get rid of type=module
(and import/export by putting the showMessage
function right in showImport.js
) everything works, but the whole purpose of this was to use modules.
我还必须添加无用的export default
语句,否则Chrome会抱怨:
Also I had to add that useless export default
statement, without it Chrome would complain:
Uncaught SyntaxError: The requested module '/show.js' does not provide an export named 'default'
那我在这里想念什么?
推荐答案
- 在模块上下文中,变量不会自动全局声明.您必须自己将它们附加到
window
.这是为了避免使用普通脚本标记时遇到的范围模糊性问题. -
导入/导出用法不正确.
- In a module context, variables don't automatically get declared globally. You'll have to attach them to
window
yourself. This is to prevent the scope ambiguity issues that you'd run into when using normal script tags. The import/export usage is incorrect.
如果您export function xyz
,则必须import { xyz }
如果您export default function xyz
,则必须import xyz
或import { default as xyz }
请牢记这一点,这就是您要得到的.
With that in mind, here's what you'd end up with.
showImport.js:
showImport.js:
import { showMessage } from '/show.js'
window.showImportedMessage = function showImportedMessage() {
showMessage()
}
show.js:
export function showMessage() {
alert("Hello!")
}
这篇关于如何通过type = module使用脚本中的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!