【问题标题】:How to use code from script with type=module [duplicate]如何使用 type=module 的脚本中的代码 [重复]
【发布时间】:2018-08-26 13:13:12
【问题描述】:

我不明白为什么这个琐碎的代码不起作用:

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) 时,我看到以下错误

(index):8 Uncaught ReferenceError: showImportedMessage is not defined
    at HTMLButtonElement.onclick ((index):8)
onclick @ (index):8

如果我摆脱 type=module(并通过将 showMessage 函数直接放入 showImport.js 来导入/导出)一切正常,但这样做的全部目的是使用模块

我还必须添加那个无用的 export default 声明,没有它 Chrome 会抱怨:

Uncaught SyntaxError: The requested module '/show.js' does not provide an export named 'default'

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

【问题讨论】:

    标签: javascript import ecmascript-6 module


    【解决方案1】:
    1. 在模块上下文中,变量不会自动全局声明。您必须自己将它们附加到window。这是为了防止您在使用普通脚本标签时遇到的范围模糊问题。
    2. 导入/导出用法不正确。

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

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

    See this article for more information on the module syntax.

    showImport.js:

    import { showMessage } from './show.js'
    
    window.showImportedMessage = function showImportedMessage() {
        showMessage()
    }
    

    show.js:

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

    【讨论】:

    • 太棒了!非常感谢。这比副本中的答案更好。
    • 你能举个第1点的例子吗?有没有比分配给窗口更好/更好的方法?
    • 分配给窗口很好。 100% 清楚地表明您正在向全局命名空间中添加某些内容(var 在传统的非模块脚本标记中没有 明确表示的内容)。例如,在一个较大的项目中,如果您不小心,您可能会意外地拥有两个名为“user”的变量。好的做法可以帮助避免此类愚蠢的问题,但模块会完全阻止它们发生。
    • @ElMac 为了在模块上下文中创建全局变量,您需要通过脚本标签将变量直接添加到 HTML,例如&lt;script&gt; let myVar; &lt;/script&gt;
    • 即使在 about:config 中将 seucity.fileurl.strictoriginpoliy 设置为 false,这也无法像 2021 年用 Firefox 编写的那样工作。如何让 index.html 中的 window 引用该函数,因为它没有。最好把它写成一个完整的例子,包括 HTML 文件。看来你猜到了,没有尝试。
    猜你喜欢
    • 1970-01-01
    • 2012-04-17
    • 2021-04-25
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2019-09-17
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多