Close

JavaScript Modules - Single Default Export

[Last Updated: Nov 28, 2018]

To export a single value we can use export default. The target feature should not necessarily have a name. The default export can also be used as fallback for importing modules.

export default function runByDefault(){ ... }
import defaultName  from "module-name"
 ...
defaultName(); //calls runByDefault() function

Where 'defaultName' is the local variable name of our choice for default feature.

Note that there's no curly-braces like named imports (last tutorial), also it's quite distinguishable from namespace import * as XYZ (second last tutorial).

Example

export default class{
  static square(a){
      return a * a;
  }
}

js/app.js

import Something from "./lib.js";

export function displaySquare(id, number) {
    let squaredValue = Something.square(number);
    document.getElementById(id).innerHTML = squaredValue;
}

index.html

<html>
<body>
<div id="display-div"></div>
<script type="module">
  import {displaySquare} from './js/app.js'
  displaySquare("display-div", 5);
</script>
</body>
</html>

output


Example Project

Dependencies and Technologies Used:

  • techUsed=Node.js v8.11.3
  • Google Chrome Browser Version 70.0.3538.102 (Official Build) (64-bit)
Default Export Example Select All Download
  • default-export
    • js
      • app.js

    See Also