Javascript Importing Modules And Using Them in HTML Document

126 views Asked by At

The problem I have been having is that I cannot get imported modules to work together in vanilla Javascript. Here's my project structure:

> toplevel
> index.html
> main.css
> main.js
> js/
> > setup_event_listeners.js

main.js:

// only import statement
import { setupEventListenersForIndex } from "./js/setup_event_listeners";

...

setup_event_listeners.js:

// only export
export function setupEventListenersForIndex() {
    addEventListenerToLambdaButton();
    addEventListenerToSubmitButton();
}

...

index.html

<body>
    ...
    <script type="module" src="./main.js"></script>
</body>

I use the Live Server VSCode Extension to host my test server. I have left the default settings as is and have not configured the settings.

When I run the Live Server, the console logs this error:

main.js:2
GET http://127.0.0.1:5500/js/setup_event_listeners net::ERR_ABORTED 404 (Not Found)

I have attempted to move the script tag around. The CSS is loading perfectly fine so I am unsure of the problem.

1

There are 1 answers

0
jQueeny On BEST ANSWER

Try adding the .js extension to your import:

import { setupEventListenersForIndex } from "./js/setup_event_listeners.js";

As stated in the Node docs:

A file extension must be provided when using the import keyword to resolve relative or absolute specifiers. Directory indexes (e.g. './startup/index.js') must also be fully specified. This behavior matches how import behaves in browser environments, assuming a typically configured server.