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.

asked Jul 8, 2020 at 22:56
7
  • Shouldn't you be invoking the hello() inside the file some_file.js Commented Jul 8, 2020 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: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules Commented Jul 8, 2020 at 23:00
  • Ok, with your modified code, your source file is not exporting anything. export function hello() ... Commented Jul 8, 2020 at 23:02
  • @Taplar Sorry, I neglected to add the type="module" in my HTML Commented Jul 8, 2020 at 23:03
  • I think you need to export the function... Commented Jul 8, 2020 at 23:03

2 Answers 2

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>
answered Jul 8, 2020 at 23:10
Sign up to request clarification or add additional context in comments.

3 Comments

Uncaught TypeError: Error resolving module specifier "some_file.js". Relative module specifiers must start with "./", "../" or "/".
Yes! This is exactly what I needed. Thank you
That's no problem. Thanks for updating the answer 👍
-2

Try this:

index.html

<script src="some_file.js" type="module">
 hello()
</script>
answered Jul 8, 2020 at 23:06

1 Comment

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)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.