DEV Community

Michael Burrows
Michael Burrows

Posted on • Edited on

ES6 Modules: How to use import and export in JavaScript

ES6 provides the ability to split JavaScript into multiple files (modules).

Modules can then be exported and imported as required into other files.

The biggest benefit of modules is they help keep large amounts of JavaScript organised.

To better understand how modules work let’s create a simple project with following files and folder structure.

|- index.html
|- app.js
|- /src
  |- location.js
  |- weather.js
Enter fullscreen mode Exit fullscreen mode

First add the following markup to the index.html file:

<!DOCTYPE html>
<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>
Enter fullscreen mode Exit fullscreen mode

Notice the type="module" so that the browser treats the script as a module, it wont work without it.

Exporting

Before we can import we must first export the code from the weather.js and location.js files.

In weather.js let’s create a weather() function with an export directive.

export function weather() {
  const temperature = "15c";
  const conditions = "Sunny"
  return temperature + " " + conditions;
}
Enter fullscreen mode Exit fullscreen mode

And in location.js we’ll export multiple variables by adding the desired members to the export directive.

const country = "Australia";
const state = "Victoria";
const city = "Melbourne";

export { country, state, city };
Enter fullscreen mode Exit fullscreen mode

Importing

Now in the app.js file we can import the external JavaScript.

import { country, state, city } from "./src/location.js";
import { weather } from "./src/weather.js";
Enter fullscreen mode Exit fullscreen mode

Once imported it can be used just as it would if it existed in the same JavaScript file.

To complete the project we’ll output the imported modules into the index.html.

const getWeather = weather();
const currentWeather = "<h2>Weather " + getWeather + "</h2>";
const currentLocation = "<h1>" + country +  " | " + state + " | " + city +  "</h1>";
document.getElementById("app").innerHTML = currentLocation + currentWeather;
Enter fullscreen mode Exit fullscreen mode

If everything is correct you should see the following when index.html is viewed in a browser.

Alt Text

Note: Modules will only work in files served via http(s) not in the local file system (file:///).

Top comments (0)