To better understand how modules work let’s create a simple project that uses imports and exports. To get started create the following files and folder structure:
|- index.html |- app.js |- /src |- location.js |- weather.js
Then add the following markup to the
<html lang="en"> <head> <meta charset="UTF-8" /> <title>Our Application</title> </head> <body> <div id="app"></div> <script type="module" src="app.js"></script> </body> </html>Code language: HTML, XML (xml)
type="module" so that the browser treats the script as a module, it wont work without it.
Before we can import we must first export the code from the
location.js files. In
weather.js let’s create a
weather() function with an
location.js we’ll export multiple variables by adding the desired members to the
Now in the
You should see the following when
index.html is viewed in a browser.
Note: Modules will only work in files served via http(s) not in the local file system (file:///).