如何使用 type=module 的脚本中的代码 [英] How to use code from script with type=module

查看:49
本文介绍了如何使用 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-server 提供服务.当我连接 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'

那么我在这里错过了什么?

So what am I missing here?

推荐答案

  1. 在模块上下文中,变量不会自动全局声明.您必须自己将它们附加到 window.这是为了防止您在使用普通脚本标签时遇到的范围模糊问题.
  2. 导入/导出用法不正确.
  1. 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.
  2. The import/export usage is incorrect.

如果你export function xyz,你必须import { xyz }

如果你export default function xyz,你必须import xyzimport { default as xyz }

有关模块语法的更多信息,请参阅这篇文章.

showImport.js:

showImport.js:

import { showMessage } from './show.js'

window.showImportedMessage = function showImportedMessage() {
    showMessage()
}

show.js:

export function showMessage() {
    alert("Hello!")
}

这篇关于如何使用 type=module 的脚本中的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆