"Cannot use import statement outside a module" and "Uncaught SyntaxError: Unexpected identifier" when importing a class

"Cannot use import statement outside a module" and "Uncaught SyntaxError: Unexpected identifier" when importing a class

我正在尝试将 class 导入到我的“main.js”文件中。这是我的代码的缩小版本。

// "extended.js" file

export default class Test {
  constructor() {
    this.prop = "Hello"
    console.log(this.prop)
  }
}


// "main.js" file

window.onload = function () {
  import Test from "./extended"
  new Test()
}

main.js 文件是我的 Express 应用程序的前端 JavaScript 文件,因此它存储在“public”文件夹中。当您加载页面时,发生的初始错误是“无法在模块外使用导入语句”。我自己做了研究,很多人都说使用 “main.js”脚本标签的 type="module" 将解决该问题。当我这样做时,错误更改为“Uncaught SyntaxError: Unexpected identifier”。关于如何使用 ES6 模块和 classes,我是否遗漏了什么?

您只能在顶层导入 - 它不能在块内完成。变化

window.onload = function () {
  import Test from "./extended"
  new Test()
}

import Test from "./extended"
window.onload = function () {
  new Test()
};

虽然,我也建议不要为副作用创建 classes - 如果你只是想让 class 做 一些事情,但是不要 return 一些有用的东西,而是使用普通函数。

export default () => {
  const prop = "Hello";
  console.log(prop);
};