简体   繁体   中英

Importing functions in javascript

Trying to use GoJS library I get an "import declarations may only appear at top level of a module" error.

main.html

...
<script id = "code">
    import {makeNodes} from "./make_nodes.js";

    function init(){
       makeNodes(model);
       ...
    }
</script>

<body onload="init()">
...

make_nodes.js

export function makeNodes(model){
    ...
}

As the error says, you can't use import except in a module. Your code isn't in a module. To make it a module, use type="module" in the script tag:

<script id = "code" type = "module">

But , note that native support for modules in browsers is very new . (Also, it doesn't work in IE, and never will.) Most people using import / export syntax are still doing so via transpilers and/or bundlers (like Webpack or Browserifty).

Once you do that, init will no longer be a global, but your <body onload="init()"> expects init to be a global. (This is one of several reason not to use onxyz -attribute-style event handlers.) To fix that, hook up the event in your code, removing the onload attribute from <body> :

function init(){
   makeNodes(model);
   // ...
}
window.addEventListener("load", init);

However , the load event you're using happens very, very late in the page load process, waiting for all images and other resources to finish loading. In most cases, you're better off running your code earlier than that by moving the script element to the very end of the document, just before the closing </body> element, and then just doing the init immediately:

<body>
<!-- presumably there's stuff here ... -->

<script id="code" type="module">
    import {makeNodes} from "./make_nodes.js";

    function init(){
       makeNodes(model);
       // ...
    }
    init();
</script>
</body>

At that point, all elements defined by the HTML above the script tag exist and can be operated upon.

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