JavaScript Tutorial Series - Modules




In JavaScript es6, modules provide the ability to use variables, methods and classes in another JavaScript file.

The following is an example to export a function from a JavaScript file for use in another JavaScript file:

export function printSomething(value) {
  console.log(value)
}

The function is exported by including the export keyword. It could also export the function like this:

function printSomething(value) {
  console.log(value)
}

export {printSomething};

Exporting multiple items would be comma separated:

printExample.js:

const season = 'Spring'

function printSomething(value) {
  console.log(value)
}

export {season, printSomething};


To use an exported item in another file, add an import as follows:

home.js:

import printExample from './printExample.js';

(function() {

  printExample.printSomething("abc");

})();


The name after the import keyword is the name of the class, function or variable being exported from the .js file.


An export can also be renamed when importing it using an alias:

home.js:

import printExample as pe from './printExample.js';

(function() {

  pe.printSomething("abc");

})();


The top level JavaScript file importing a module, must be included in an html or php file using a type of module:

index.html:

<html>
  <head>

  </head>

  <body>

    <script src="home.js" type="module"></script>
  </body>
</html>



Implementation:




If you have been following along with the JavaScript Tutorial Series, take a look at modules/TemperatureConverter.js and modules/Weather.js. These are both JavaScript modules. They both are used by the javascript_tutorial.js file.

In TemperatureConverter.js and Weather.js, notice the export default statements at the end of each file. These statements export the entire TemperatureConverter and Weather classes for use by other JavaScript files.

In javascript_tutorial.js, notice the following lines at the top of the file:


import TemperatureConverter from "./modules/TemperatureConverter.js";
import Weather from "./modules/Weather.js";


These lines import the entire TemperatureConverter and Weather classes.

Further down, those names will be used to access functionality within its class.


For this implementation, there aren't any file changes.

For completeness, each file in the tutorial is shown below:


<html>
  <head>
    <link rel="stylesheet" href="css/style.css"/>
  </head>

  <body>
    <header>
      <nav>

      </nav>

      <article id="toolbar">
        <article id="currentWeather" class="text-center">
          <section id="location">
          </section>
          <section id="weatherTemperature">
            <span id="temperatureValue"></span>
            <span id="degreeSymbol">°</span>
            <span id="temperatureUnits"></span>
          </section>
          <section id="weatherDescription">
          </section>
          <img id="weatherIcon">                
          </img>
        </article>          
      </article>

    </header>

    <main></main>

    <footer></footer>

    <script src="js/javascript_tutorial.js" type="module"></script>
  </body>
</html>



js/javascript_tutorial.js:



// JavaScript Tutorial

/*
 * This file will add JavaScript
 * to a website.
 */
import TemperatureConverter from "./modules/TemperatureConverter.js";
import Weather from "./modules/Weather.js";

(function() {
  let doc = document;
  let defaultLocation = [-86.7816, 36.1627]; // longitude, latitude

  function setWeather(data) {
    if (data) {
      let temp = Math.round(data.main.temp);
      try {
        let fahrenheit = TemperatureConverter.convertCelsiusToFahrenheit(temp - 273);
        console.log("Fahrenheit temperature: " + fahrenheit);
      } catch (error) {
        console.log("Error setting weather: " + error.message);
      }
    }
  }

  function init() {
    let locationStr = "";
    for (let i = 0, num = defaultLocation.length; i < num; i++) {
      locationStr += defaultLocation[i];
      if (i === 0) {
        locationStr += ", ";
      }
    }

    console.log("Setting weather for location: " + locationStr);

    setWeather({ main: { temp: 30 } });
  }

  init();
})();



js/modules/TemperatureConverter.js:



class TemperatureConverter {
  
    static convertKelvinToCelsius(kelvin) {
        if (typeof kelvin !== 'number') {
            throw 'Kelvin value is not a number';
        }
        return Math.round(kelvin - 273);
      }
    
      static convertCelsiusToFahrenheit(celsius) {
        if (typeof celsius !== 'number') {
            throw 'Celsius value is not a number';
        }
        return Math.round((celsius * (9/5)) + 32);
      };
    
      static convertFahrenheitToKelvin(fahrenheit) {
        if (typeof fahrenheit !== 'number') {
            throw 'Fahrenheit value is not a number';
        }
        return Math.round(((5/9) * (fahrenheit - 32)) + 273);
    };
}

export default TemperatureConverter;



js/modules/Weather.js:



class Weather {

    // Constructor
    constructor() {
    };

    getLocation() {
        let url = 'https://ipinfo.io/json';
        let options = {
            mode : 'cors'
        };
    };

    getWeather(coordinates) {
       }  
    }

export default Weather;



css/style.css:




header nav {
  height: 10vh;
  border-bottom: 1px solid darkgray;
}

header #toolbar {
  height: 5vh;
  border-bottom: 1px solid darkgray;
}

main {
  height: 72vh;
  border-bottom: 1px solid darkgray;
}

footer {
  height: 10vh;
  border-bottom: 1px solid darkgray;
}



You should see the following in the browser console when loading the index.html file:

Setting weather for location: -86.7816, 36.1627
javascript_tutorial.js:19 Fahrenheit temperature: -405


Note, the files will need to be loaded onto a web server. If running them locally in Chrome, you may get a CORS error.


The JavaScript tutorial series starts with this post.


(paid links)

More JavaScript





Comments