【问题标题】:How to access function from a javascript type=module如何从 javascript type=module 访问函数
【发布时间】:2021-11-30 13:37:23
【问题描述】:

我有三个文件,分别是index.htmlmodule.jsmain.jsindex.js

INDEX.HTML

....
<body
    <script type="module "src="main.js"></script>
    <script src="index.js"></script>
</body>
...

MODULE.JS

....
function foo(text){
  alert(text)
}

export default foo;
...

MAIN.JS

import foo from "./module.js"
function bar(text){
   foo("FOOBAR")
}

INDEX.JS

bar() // not "type="module"

我可以从index.js 执行bar() 而不在html 中提供type="module" 属性吗?

【问题讨论】:

  • 据我所知,模块不声明全局变量。因此它们不能作为“栏”使用,您需要导入它们或从模块本身使它们成为全局
  • "我可以从 index.js 执行 bar() ..." - 不,一旦文件被声明为模块,它就变成了一个闭包,就好像它是它自己的命名空间。访问其功能的唯一方法是导入它们。

标签: javascript module


【解决方案1】:

这是不可能的。正如 Ruben 在评论中提到的,您需要将 main.js 导入您的 index.js 才能访问其 bar() 函数,否则您将获得一个

Uncaught ReferenceError: bar is not defined

错误

检查这些问题可能会有所帮助:

how-to-use-code-from-script-with-type-module

use-functions-defined-in-es6-module-directly-in-html

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多