How to use code from script with type=module [duplicate]

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

Leave a Comment