How to use code from script with type=module

JavascriptImportEcmascript 6Module

Javascript Problem Overview


I can't figure out why this trivial code is not working:

index.html:

<!doctype HTML>
<html>

<head>
  <script type="module" src="/showImport.js"></script>
</head>

<body>
  <button onclick="showImportedMessage();">Show Message</button>
</body>

</html>

showImport.js:

import showMessage from '/show.js';

function showImportedMessage() {
    showMessage();
}

show.js:

export default "Why do I need this?";

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

It is being served by NPM http-server. When I connect with Chrome (v65), I see the following error

(index):8 Uncaught ReferenceError: showImportedMessage is not defined
    at HTMLButtonElement.onclick ((index):8)
onclick @ (index):8

If I get rid of type=module (and import/export by putting the showMessage function right in showImport.js) everything works, but the whole purpose of this was to use modules.

Also I had to add that useless export default statement, without it Chrome would complain:

Uncaught SyntaxError: The requested module '/show.js' does not provide an export named 'default'

So what am I missing here?

Javascript Solutions


Solution 1 - Javascript

  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!")
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontromgyView Question on Stackoverflow
Solution 1 - JavascriptkingdaroView Answer on Stackoverflow