Help Importing JS files

Hi there,

I’m trying to export a js function and import it into another file. My setup is,
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="index.js"></script>
    <title>ES6</title>
</head>
<body>
</body>
</html>

animal.js

export function test() {
    console.log('Hello')
}

index.js

import { test } from './module/animal';
 
test()

I’m using VSCode and the Live Server extension and firefox as my browser. The error message I’m getting in the browser console is…

Uncaught SyntaxError: import declarations may only appear at top level of a module

I’ve tried adding the type module to my index.html file and I receieve the error…

Loading module from “http://127.0.0.1:5500/module/animal” was blocked because of a disallowed MIME type (“text/html”)

Please Help!

1 Like

Hi @tjryan

Welcome to FCC.
Try out the following

  • Change <script src="index.js"></script> to become <script src="./index.js"></script>
  • Change import { test } from './module/animal' to become import { test } from './module/animal.js'
1 Like

Also, script needs to have type="module".

<script type="module" src="./index.js"></script>
1 Like

@tjryan

You might want to take a look at this blog post about the HTML boilerplate,

It shows where the script tags would need to go (at the bottom before the </html>)

Hope this helps!
Best,
Cy499_Studios

1 Like

That isn’t valid JS, imports have to be fully qualified:

import { test } from './module/animal.js';

And yeah,

<script src="index.js" type="module"></script>

Is mandatory.

Side issue re above post, it doesn’t have to be anywhere specific, can be in head or body, once you add type=“module” the script is automatically deferred, the advice there doesn’t really apply.

1 Like

Thank you so much for the help everyone! I’ve been learning javascript and web development mostly on my own and have run into headaches that have taken me a while to figure out. Having a great community like this to be part of is making me so excited to continue on my journey!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.