简体   繁体   中英

function in my javascript module is not defined

I'm writing JavaScript for the browser, my script.js has something like

import { foo, bar } from "./lib/sth.js"
function main() { ... }

Then I have this in my browser:

<script type=module src="./script.js"></script>
<body onload="main();"> ... </body>

But it's keep giving me this error:

Uncaught ReferenceError: main is not defined at onload ((index):7)

Why is my main now defined? It works fine before I use type=module, but with the import statement, I believe it has to be type=module

Thanks for @HereticMonkey and @FelixKling!

window.onload = function() { ... } 

does work for my problem. Yet I'm confused why import is designed like this. Suppose I just wanna use some library in my script so I import it, why this makes my script has to be a module as well?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM