代码之家  ›  专栏  ›  技术社区  ›  tromgy

如何使用类型为module[重复]的脚本中的代码

  •  66
  • tromgy  · 技术社区  · 8 年前

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

    指数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();
    }
    

    显示js公司:

    export default "Why do I need this?";
    
    export function showMessage() {
        alert("Hello!");
    }
    

    NPM正在为其提供服务 http服务器 . 当我连接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'
    

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

    1 回复  |  直到 6 年前
        1
  •  105
  •   kingdaro    4 年前
    1. 在模块上下文中,变量不会自动全局声明。您必须将它们连接到 window 你自己这是为了防止在使用普通脚本标记时遇到的范围模糊问题。
    2. 导入/导出用法不正确。

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

    如果你 export default function xyz ,您必须 import xyz 或 import { 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()
    }
    

    显示js公司:

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