Javascript 如何使用带有 type=module 的脚本中的代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49338193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use code from script with type=module
提问by tromgy
I can't figure out why this trivial code is not working:
我不明白为什么这个微不足道的代码不起作用:
index.html:
索引.html:
<!doctype HTML>
<html>
<head>
<script type="module" src="/showImport.js"></script>
</head>
<body>
<button onclick="showImportedMessage();">Show Message</button>
</body>
</html>
showImport.js:
显示导入.js:
import showMessage from '/show.js';
function showImportedMessage() {
showMessage();
}
show.js:
显示.js:
export default "Why do I need this?";
export function showMessage() {
alert("Hello!");
}
It is being served by NPM http-server. When I connect with Chrome (v65), I see the following error
它由 NPM http-server 提供服务。当我连接 Chrome (v65) 时,我看到以下错误
(index):8 Uncaught ReferenceError: showImportedMessage is not defined
at HTMLButtonElement.onclick ((index):8)
onclick @ (index):8
If I get rid of type=module(and import/export by putting the showMessagefunction right in showImport.js) everything works, but the whole purpose of this was to use modules.
如果我摆脱type=module(并通过将showMessage函数放入正确的导入/导出showImport.js)一切正常,但这样做的全部目的是使用 modules。
Also I had to add that useless export defaultstatement, without it Chrome would complain:
另外我不得不添加那个无用的export default声明,没有它Chrome会抱怨:
Uncaught SyntaxError: The requested module '/show.js' does not provide an export named 'default'
So what am I missing here?
那么我在这里错过了什么?
回答by kingdaro
- In a module context, variables don't automatically get declared globally. You'll have to attach them to
windowyourself. This is to prevent the scope ambiguity issues that you'd run into when using normal script tags. The import/export usage is incorrect.
If you
export function xyz, you mustimport { xyz }If you
export default function xyz, you mustimport xyzorimport { default as xyz }
- 在模块上下文中,变量不会自动全局声明。您必须将它们附加到
window自己身上。这是为了防止您在使用普通脚本标签时遇到的范围模糊问题。 导入/导出用法不正确。
如果你
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:
显示导入.js:
import { showMessage } from '/show.js'
window.showImportedMessage = function showImportedMessage() {
showMessage()
}
show.js:
显示.js:
export function showMessage() {
alert("Hello!")
}

