How to Use Code from Script with Type=Module

How to use code from script with type=module

  1. In a module context, variables don't automatically get declared globally. You'll have to attach them to window yourself. This is to prevent the scope ambiguity issues that you'd run into when using normal script tags.
  2. The import/export usage is incorrect.

If you export function xyz, you must import { xyz }

If you export default function xyz, you must import xyz or import { default as xyz }

See this article for more information on the module syntax.

showImport.js:

import { showMessage } from './show.js'

window.showImportedMessage = function showImportedMessage() {
showMessage()
}

show.js:

export function showMessage() {
alert("Hello!")
}

How to call a function declared in a javascript module (type=module) from an html page

First of all you have to explicitly export you function:

export function greet() {
alert("Hello from module");
}

Secondly, a module has it's own scope (this is the whole point of modules) thus you need to add the function to the global scope. So, to do it you have to run a script which imports the function and adds it to the window object:

<script type="module">
import { greet } from "./app.js";
window.greetFromModule = greet;
</script>

Now you don't need this part <script type="module" src="app.js"></script>

Alternatively you can create an empty obj and add your modules stuff to it, this is what it would look like:

<html>
<head></head>
<body>
<button onclick="greetFromHtml();">greetFromHtml</button>
<button onclick="module.greet()">greetFromModule</button>
<script type="text/javascript">
function greetFromHtml() {
alert("Hello");
}
const module = {};
</script>
<script type="module">
import { greet } from "./app.js";
module.greet = greet;
</script>
</body>
</html>

How to access function from a javascript type=module

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



Related Topics



Leave a reply



Submit