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?

2
  • 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 Commented Nov 30, 2021 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. Commented Nov 30, 2021 at 13:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.