Close

JavaScript Modules - Different ways to Export

[Last Updated: Nov 30, 2018]

Following are different ways of exporting features:

  1. Inline Named Export Declaration

    export function doSomething1() {.....}
    export function doSomething2(){....}
    This is what we have been doing in previous tutorials.
  2. Separate export clause with variable statement

    export {doSomething1, doSomething2}
    function doSomething1() {.....}
    function doSomething2(){....}
  3. Export clause with different names

    export {doSomething1 as run1, doSomething2 as run2}
    function doSomething1() {.....}
    function doSomething2(){....}
    export {doSomething1, doSomething2 as run2}
    function doSomething1() {.....}
    function doSomething2(){....}
  4. Default export

    export default function doSomethingByDefault(){.....}
    
    Check out tutorial here

Example

js/lib.js

export let name = "library 1"

export default function message() {
    show("hi there!");
}

export function showSum(x, y) {
    show(x + y);
}

function show(result) {
    console.log(result);
}

js/lib2.js

export {desc, PI, showSquare, Task as Runner}
let desc = "liberal 2";

const PI = Math.PI;

function showSquare(x) {
    console.log(x * x);
}

class Task {
    run() {
        console.log("running");
    }
}




js/app.js

import defaultFunction, * as util1 from "./lib.js";
import * as util2 from "./lib2.js";

defaultFunction();
console.log(util1.name);
util1.showSum(3, 5);
console.log("---");
console.log(util2.desc);
util2.showSquare(4);
console.log(util2.PI);
let runner = new util2.Runner();
runner.run();

Output

To try examples, run http-server from project root:

$ http-server

On loading index.html in the browser, we get following output in the console window:

hi there!
library 1
8
---
liberal 2
16
3.141592653589793
running

Example Project

Dependencies and Technologies Used:

  • Node.js v8.11.3
  • Google Chrome Browser Version 70.0.3538.102 (Official Build) (64-bit)
Different ways to Export Select All Download
  • javascript-export-syntaxes
    • js
      • lib2.js

    See Also