How to use code from script with type=module [duplicate]
- 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. The import/export usage is incorrect.
If you
export function xyz
, you mustimport { xyz }
If you
export default function xyz
, you mustimport xyz
orimport { default as xyz }
With that in mind, here's what you'd end up with.
showImport.js:
import { showMessage } from '/show.js'window.showImportedMessage = function showImportedMessage() { showMessage()}
show.js:
export function showMessage() { alert("Hello!")}