Section 32 – Lesson 424 – Complete 2020 Web Development Bootcamp

Lesson 424 – Javascript ES6 – Import, Export and Modules

You can use the export function to export either a single piece of information or multiple pieces of information. In the math.js file below, the information contained in the constant variable “pi” is exported by “export default pi;” and the two functions are exported by “export {doublePi, triplePi};”.

const pi = 3.1415962;

function doublePi() {
  return pi * 2;
}

function triplePi() {
  return pi * 3;
}

export default pi;

export {doublePi, triplePi};

The code contained in the index.js file imports the information contained in the math.js file and uses it by inserting it as javascript in the html list elements –

import React from "react";
import ReactDOM from "react-dom";
import pi, { doublePi, triplePi } from "./math.js";

ReactDOM.render(
  <ul>
    <li>{pi}</li>
    <li>{doublePi()}</li>
    <li>{triplePi()}</li>
  </ul>,
  document.getElementById("root")
);

Instead of importing individual pieces of information using this code –

import pi, { doublePi, triplePi } from "./math.js";

– you can also import everything contained in the math.js file using an “*” as a wildcard like this –

import * as pi from "./math.js";

Then we have to refactor the html elements in the index.js file like this –

<ul>
    <li>{pi.default}</li>
    <li>{pi.doublePi()}</li>
    <li>{pi.triplePi()}</li>
  </ul>,

The refactored index.js file now looks like this –

import React from "react";
import ReactDOM from "react-dom";
import * as pi from "./math.js";

ReactDOM.render(
  <ul>
    <li>{pi.default}</li>
    <li>{pi.doublePi()}</li>
    <li>{pi.triplePi()}</li>
  </ul>,
  document.getElementById("root")
);