Close

JavaScript Modules - Declaring a Module To only Export Other Modules

[Updated: Dec 8, 2018, Created: Dec 7, 2018]

A module can be declared for the sole purpose for re-exporting other modules, so that multiple imports can be reused by different client modules.

Example

js/lib1.js

export function getSquareRoot(x) {
    return Math.sqrt(x);
}

js/lib2.js

export function getCubicRoot(x) {
    return Math.cbrt(x);
}

js/lib3.js

export function getSquareSum(a, b) {
    return Math.pow(a, 2) + Math.pow(b, 2);
}

js/MathLib.js

export * from "./lib1.js";
export * from "./lib2.js";
export * from "./lib3.js";

js/app.js

import * as mathUtil from "./MathLib.js";

console.log(mathUtil.getSquareSum(3, 5));
console.log(mathUtil.getSquareRoot(5));
console.log(mathUtil.getCubicRoot(7));

index.html

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

</body>
</html>

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

$ http-server

Loading index.html in browser, gives following console output:

34
4 2.23606797749979
5 1.9129311827723892

Example Project

Dependencies and Technologies Used:

  • Node.js v8.11.3
  • Google Chrome Browser Version 70.0.3538.110 (Official Build) (64-bit)
A Module To Export Other Modules Select All Download
  • javascript-transitive-re-exports
    • js
      • MathLib.js

    See Also