Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS import module and run on page load

I want to call my function main() using html onload event and console.log text imported from another (generateObject.js) file, but when I import function, onload event stop working and function main() is not anymore used.

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();

When I try console.log("text") in main() it works but when I try to use imported function it's not. What should I do to fix that?

Errors in Chrome console:

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)
like image 849
RageZ Avatar asked Apr 05 '20 19:04

RageZ


2 Answers

modules will have its own scope. They are not available in the global scope like the normal scripts. So it's accessible only inside main.js in your case.

To make it work you need to add it to global scope explicitly.

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

window.main = main;

Alternatively, you can remove the event handler from HTML and add it in the JS file.

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)
like image 80
SpiritOfDragon Avatar answered Oct 14 '22 14:10

SpiritOfDragon


generateObject.js:

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

main.js:

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

main();

Working example

like image 35
aopanasenko Avatar answered Oct 14 '22 14:10

aopanasenko