JS import problem

Hey,

I have a problem with a simple import from one js file to another.

test.js:

import { sayHi } from './test2.js'

sayHi('Sam')

test2.js:

export function sayHi(user) {
    console.log(`Hello, ${user}!`);
  }

The error I get:

import {sayHi} from './test2.js'
^^^^^^

SyntaxError: Cannot use import statement outside a module

I’ve tried importing with and without brackets, using export default, and still getting the same message.
I’m using VS Code and have the latest Node installed.

Any help will be appreciated!

How exactly are you trying to execute the above code?

What does the script tag look like, on the page that brings in the test.js file?

In the nearest parent package.json file do you have "type": "module"?

https://nodejs.org/api/esm.html#esm_enabling

1 Like

Yeah, I guess that leads to a first question I should have asked - is this front-end import, or back-end import??

1 Like

Good point, I’ve maybe wrongly assumed it was back-end.

1 Like

Nope, I think you were valid in your assumption. I belive the OP had edited the question since yesterday, added the bit about node after I’d asked.

But either way, the question remains - the issue is in the importing of the first js file. Whether in the package.json or in the HTML file.

In the case of the HTML file, it might be as simple as

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

Adding the type to the import is what I’ve had to do to fix that. And, of course, using a modern browser that handles imports. :wink:

1 Like

Thank you for your answers everyone!

Actually I have an array of images and I’m trying to import them into another JS file so I can create an image gallery. I only wrote this simple code for the sake of example.

After setting type="module" in my html file I got the following error in the browser:

Loading module from *filepath* was blocked because of a disallowed MIME type (“text/html”).

Can you show us the code in all the files you are now using?

I think I managed to overreact a simple problem. :sweat_smile:

Anyway, solved it!

I just forgot to include the ‘.js’ at the end of the filename in the import statement. * facepalm *

Thank you for the replies!

1 Like