简体   繁体   English

用javascript导入函数

[英]Importing functions in javascript

Trying to use GoJS library I get an "import declarations may only appear at top level of a module" error. 尝试使用GoJS库时, 出现“导入声明可能仅出现在模块的顶层”错误。

main.html main.html

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

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

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

make_nodes.js make_nodes.js

export function makeNodes(model){
    ...
}

As the error says, you can't use import except in a module. 正如错误所言,您不能在模块中使用import Your code isn't in a module. 您的代码不在模块中。 To make it a module, use type="module" in the script tag: 要使其成为模块,请在script标签中使用type="module"

<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). (此外,它在IE中也不起作用,永远不会。)大多数使用import / export语法的人仍然通过编译器和/或打包程序(例如Webpack或Browserifty)来这样做。

Once you do that, init will no longer be a global, but your <body onload="init()"> expects init to be a global. 一旦这样做, init将不再是全局的,但是您的<body onload="init()">希望init是全局的。 (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> : (这是不使用onxyz -attribute风格的事件处理程序的几种原因之一。)要解决此问题,请在代码中挂接事件,从<body>删除onload属性:

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. 但是 ,您正在使用的load事件在页面加载过程的非常非常晚的时候发生,等待所有图像和其他资源完成加载。 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: 在大多数情况下, 最好script元素移到文档的最后,即在</body>元素之前,然后立即执行init:

<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. 到那时, script标记上方的HTML定义的所有元素都存在并且可以对其进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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