JS 导入模块并在页面加载时运行

Rag*_*geZ 3 javascript import module export

我想使用从另一个 (generateObject.js) 文件导入的 html onload 事件和 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>
Run Code Online (Sandbox Code Playgroud)

生成对象.js:

export function hello() {
    return "Hello";
}
Run Code Online (Sandbox Code Playgroud)

主要.js:

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

main();
Run Code Online (Sandbox Code Playgroud)

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

Chrome 控制台中的错误:

未捕获的语法错误:不能在模块外使用导入语句 (main.js:1)

index.html:8 Uncaught ReferenceError: main 未在加载时定义 (index.html:8)

Spi*_*gon 5

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

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

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

window.main = main;
Run Code Online (Sandbox Code Playgroud)

或者,您可以从 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>
Run Code Online (Sandbox Code Playgroud)

主文件

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

window.addEventListener('load', main)
Run Code Online (Sandbox Code Playgroud)

  • 将 main.js 引用更改为 `&lt;script type="module" src="main.js"&gt;&lt;/script&gt;` (3认同)