1

some_file.js

console.log("!")
function hello(){ 
    console.log("Hello!")
}

index.html

<script src="some_file.js" type="module"></script>
<script>
    hello()
</script>

When hosting and looking at index.html, I recieve a ReferenceError telling me that hello is not found. Following the advice to this thread other similar ones, I've placed something like window.hello = hello in my javascript file to no avail. I've also attempted exporting the function (which I think I'd only need to do if I were importing it in another javascript file).

Why am I getting a ReferenceError? The script is certainly being loaded, because I see the ! print out in the console, but the function isn't being found.

AmagicalFishy
  • 1,249
  • 1
  • 12
  • 36
  • Shouldn't you be invoking the hello() inside the file some_file.js – Rahul Kadukar Jul 08 '20 at 23:00
  • I'm slightly confused. You do not appear to be using modularized javascript with these two files. You're simply creating a js file that defines a method and including it on the html page. That's not what is commonly referred to as "modular". Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules – Taplar Jul 08 '20 at 23:00
  • Ok, with your modified code, your source file is not exporting anything. `export function hello() ...` – Taplar Jul 08 '20 at 23:02
  • @Taplar Sorry, I neglected to add the `type="module"` in my HTML – AmagicalFishy Jul 08 '20 at 23:03
  • I think you need to export the function... – evolutionxbox Jul 08 '20 at 23:03
  • @evolutionxbox I mentioned that I've tried exporting it to no avail – AmagicalFishy Jul 08 '20 at 23:04
  • @Sven.hig Yes, but—in my original file—I'm importing the `d3` library, and this does not work unless I use `type="module"` because imports have to be at the top level of a module. – AmagicalFishy Jul 08 '20 at 23:06

2 Answers2

2

Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules You have to export the function, then within a script tag with type module, import the module you want to use.

some_file.js

console.log("!")
export function hello(){ 
    console.log("Hello!")
}

index.html

<script type='module'>
    import {hello} from "./some_file.js" 
    hello()
</script>
scrappedcola
  • 10,423
  • 1
  • 32
  • 43
-2

Try this:

index.html

<script src="some_file.js" type="module">
    hello()
</script>
  • This is not valid; when the type is module, there cannot be any text in between the script tags (else the error `Expected expression, got <` comes up) – AmagicalFishy Jul 08 '20 at 23:08