【问题标题】:Can't reference javascript functions from a module [duplicate]无法从模块中引用 javascript 函数 [重复]
【发布时间】:2020-08-06 16:50:53
【问题描述】:

我有一个简单的 html 页面,它引用了一个 javascript 模块:

<head>
    <script type="module" src="mymodule.js"></script>
</head>

<body onload="doStuff()">
    . . . 

javascript 文件如下所示:

export function doStuff() {
    console.log('test');

但是,当我运行它时,我得到了错误:

columns.html:8 Uncaught TypeError: doStuff is not a function
    at onload (myPage.html:8)

如果我将 HTML 更改为:

<script src="mymodule.js"></script>

然后它起作用了;但是,这不允许我从 mymodule.js 引用第二个 javascript 库。我的问题是,为什么它作为一个模块引用时找不到函数?

【问题讨论】:

  • &lt;script type="module" src="mymodule.js"&gt;&lt;/script&gt; 不应该在 html 脚本的底部而不是在头部吗?也许我错了。
  • 为什么不使用DOMContentLoaded事件
  • 我把&lt;script type="module" src="mymodule.js"&gt;&lt;/script&gt;放在哪里似乎并不重要

标签: javascript html


【解决方案1】:
<script>
  import { doStuff } from 'mymodule.js';
</script>
<body onload="doStuff()">
....
</body>

【讨论】:

  • 恐怕这没什么区别
猜你喜欢
  • 2012-11-29
  • 2013-04-19
  • 2018-01-25
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
相关资源
最近更新 更多