页面加载时的 JS 导入模块和 运行

JS import module and run on page load

我想使用 html onload 事件和从另一个 (generateObject.js) 文件导入的 console.log 文本调用我的函数 main(),但是当我导入函数时,onload 事件停止工作正常,功能 main() 不再使用。

html:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="main.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  </head>
  <body onload="main()">
  </body>
</html>

generateObject.js:

export function hello() {
    return "Hello";
}

main.js:

import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

main();

当我在 main() 中尝试 console.log("text") 时,它起作用了,但是当我尝试使用导入函数时,它却不起作用。 我应该怎么做才能解决这个问题?

Chrome 控制台中的错误:

Uncaught SyntaxError: Cannot use import statement outside a module (main.js:1)

index.html:8 Uncaught ReferenceError: main is not defined at onload (index.html:8)

generateObject.js:

export function hello() {
    return "Hello";
}

main.js:

import { hello } from './generateObject.js';
function main(){
      console.log(hello());
} 

main();

Working example

您应该在 main.js 末尾添加对 main 函数的调用。尝试在文件底部写入 [​​=10=]。

模块将有自己的范围。它们不像普通脚本那样在全局范围内可用。因此,在您的情况下,它只能在 main.js 内部访问。

要使其正常工作,您需要将其显式添加到全局范围。

import { hello } from './generateObject.js';
function main(){
      console.log(hello());
}

window.main = main;

或者,您可以从 HTML 中删除事件处理程序并将其添加到 JS 文件中。

html

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="main.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  </head>
  <body>
  </body>
</html>

main.js

import { hello } from './generateObject.js';
function main(){
      console.log(hello());
} 

window.addEventListener('load', main)