RageZ
RageZ

Reputation: 197

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)

Upvotes: 13

Views: 12220

Answers (3)

SpiritOfDragon
SpiritOfDragon

Reputation: 1432

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)

Upvotes: 16

Lautaro Lobo
Lautaro Lobo

Reputation: 3

You should add at the end of main.js a call to the main function. Try writing main(); at the bottom of the file.

Upvotes: 0

aopanasenko
aopanasenko

Reputation: 478

generateObject.js:

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

main.js:

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

main();

Working example

Upvotes: 1

Related Questions