Export and Import Javascript

I am trying to export a module to another js file but I can’t see to make this work for some reason.

My root folder looks like this: root > css, img, js, sass and some html files. Within the js folder I have two js files: app.js and Data.js

This is how I am trying to do the export: export const data = [1, 2, 3, 4, 5]; from the Data.js file. As for the import: import {data} from './Data.js'; to the app.js file.

When I try to console.log(data); I get an error in the console: “Unexpected token {”

What am I missing here?

edit: import {data} from './Data'; this doesn’t work either…

How is your module builder set up?

Nvm, I thought I didn’t need a module builder to use these features, but then I found out that I do. I have to delete this question :sweat_smile:

Thanks for replying btw.

I try the same as Gilbert1391 and it does not work.
I thought i just need a file “data.js” with an export statement and use-data file with an import statement and i can use datas from data.js in the second use-data file.
I never heard from a module builder. What is this?

Ah ok. Thank you for your answer.

<script src="data.js" type="module"></script>
<script src="use-data.js" type="module"></script>

You have to tell the browser you’re using modules (also make sure you’re on latest Chrome/FF/Edge/Safari). Should Just Work once you’ve done that.

Note that a module bundler is necessary if your code is actually going on a real site; there is no guarantee that any user will be using a newer browser that recognises modules. And if you’re using any libraries, again you’re generally gonna need a bundler. But for just working locally with files you’re writing, that will work fine.

1 Like

It’s awesome! Really nice being able to develop simple things without having any kind of build process. You’ve got to be careful with the file paths to make sure the browser can find things, but otherwise works great. Whether it’s going to usable in production anytime in the next few years though…