Let's assume that you have the following folder structure:
terminal├── index.html ├── export.js ├── import.js
To be able to import and export modules, include Babel.
Further, define both scripts as type = "text/babel"
and data-type = "module"
. This allows to define a script as a module, and declare it as Babel type at the same time.
Let's define index.html
to see how to do it:
html<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Hello, world</title> <script src = "https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <p>Hello, world</p> <script src = "./export.js" type = "text/babel" data-type = "module"></script> <script src = "./import.js" type = "text/babel" data-type = "module"></script> </body> </html>
Let's export a JSON from export.js
:
javascriptexport default { "Erik": { "age": 30, "city": "Barcelona" }, "Andrea": { "age": 27, "city": "Barcelona" } }
Now you can import the data from import.js
:
javascriptimport siblings from './export.js'; console.log(` Siblings ages are ${siblings['Erik'].age} and ${siblings['Andrea'].age}. `);
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.