3

I have three files, let it be index.html, module.js, main.js, index.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"

Can I execute bar() from index.js without giving attribute type="module" in html?

ProHeh
  • 77
  • 1
  • 6
  • As far as I know modules don't declare global variables. Hence they won't be available as "bar", you need to import them or make them global from the module itself – Ruben Yeghikyan Nov 30 '21 at 13:45
  • "_Can I execute bar() from index.js ..._" - NO, once a file is declared as a module, it becomes a closure, as if it is its own namespace. The only way to access its features is to import them. – Randy Casburn Nov 30 '21 at 13:57

1 Answers1

0

That's not possible. As Ruben mentioned in the comment, you need to import the main.js into your index.js to have access to its bar() function, else you will get a

Uncaught ReferenceError: bar is not defined

error

Checking these questions may be helpful :

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

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

mohsen dorparasti
  • 8,107
  • 7
  • 41
  • 61