【问题标题】:Calling a Javascript Function In a Module Type Script From A Normal Script从普通脚本调用模块类型脚本中的 Javascript 函数
【发布时间】:2023-03-17 01:41:01
【问题描述】:

我想知道是否有一种方法可以从普通脚本调用模块类型脚本中的 Javascript 函数。

例如:

HTML:

<body>
   <button onclick="myFunction()">Click Here</button>
</body>

普通脚本:

function myFunction() {
   alert("Calling Module Function!");
   moduleFunction();
}

模块脚本:

/// Module stuff that requires this to be a module script

function moduleFunction() {
   alert("This was called from inside a module script");
   // Info only accessible inside module script
}

我已经在我的网站上尝试了上面的代码,但我只收到了一个Uncaught Reference 未定义函数名的错误。为了在整个脚本中使用函数,我必须采取更多步骤吗?

谢谢!

【问题讨论】:

  • JS 模块/库所有export 的东西你需要import,无论是单个方法还是提供这些方法的对象。你是如何imported 模块/库的?
  • @jmargolisvt 不,我没有。我应该导入该功能吗?也许import { moduleFunction } from ...?我不知道 from 会是什么,因为这些都在一个 HTML 文件中。

标签: javascript function module


【解决方案1】:

您可以从 module.js 导出并导入 main.js,但两者都需要为 &lt;script type='module'&gt;

/// Module.js
export function moduleFunction() {
   alert("This was called from inside a module script");
   // Info only accessible inside module script
}


// Main.js
import {moduleFunction} from Module.js

function myFunction() {
   alert("Calling Module Function!");
   moduleFunction();
}
 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

【讨论】:

  • 如果两个脚本都在 HTML 文件中,你知道我会从哪里导入它吗?
猜你喜欢
  • 1970-01-01
  • 2018-06-14
  • 2023-04-10
  • 1970-01-01
  • 2018-08-31
  • 2018-07-02
  • 2021-12-11
  • 1970-01-01
  • 2018-12-07
相关资源
最近更新 更多