且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过type = module使用脚本中的代码

更新时间:2023-12-05 08:38:58

  1. 在模块上下文中,变量不会自动全局声明.您必须自己将它们附加到window.这是为了避免使用普通脚本标记时遇到的范围模糊性问题.
  2. 导入/导出用法不正确.

  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.

如果您export function xyz,则必须import { xyz }

如果您export default function xyz,则必须import xyzimport { default as xyz }

请参阅本文,以获取有关模块语法的更多信息.

请牢记这一点,这就是您要得到的.

With that in mind, here's what you'd end up with.

showImport.js:

showImport.js:

import { showMessage } from '/show.js'

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

show.js:

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