ES6 specification allows a module to re-export the imported features from other module.
Re-exporting everything from otherModule's exports:
import * as otherModuleStuff from "otherModule";
export * from "otherModule";
.....
Re-exporting selectively:
import * as otherModuleStuff from "otherModule";
export {func1, func2 as otherFunction} from "otherModule";
.....
Exporting default:
import * as otherModuleStuff from "otherModule";
export {default} from "otherModule";
Exporting a feature of otherStuff as current module's default:
import * as otherModuleStuff from "otherModule";
export {func1 as default} from "otherModule";
The above two default exporting cannot be used at a time.
Example
js/lib2.jsexport default function help() {
console.log("available function from lib2: getCubicRoot(x)");
}
export function getCubicRoot(x) {
return Math.cbrt(x);
}
export const xyz = 123;
export const desc = "lib2 description";
js/lib1.jsimport * as mathUtil from "./lib2.js";
export {default} from "./lib2.js"; //exporting default from lib2
/*following is commented because there should be only one default*/
//export {desc as default} from "./lib2.js"; //exporting desc from module lib2 as default
export {xyz as constNum, getCubicRoot} from "./lib2.js"; //exporting other stuff from lib2
export function getCubicRootSum(x, y) {
return mathUtil.getCubicRoot(x) + mathUtil.getCubicRoot(y);
}
//following is not possible as there should be only one default
/*export default function(){
console.log("this is ./lib2's default function");
}*/
js/app.jsimport * as util from "./lib1.js";
let sum = util.getCubicRootSum(2,3);
console.log(sum);
let cubicRoot = util.getCubicRoot(27);
console.log(cubicRoot);
console.log(util.constNum);
util.default(); // lib2#help()
//console.log(util.default); lib2#desc
index.html<html>
<script type="module" src="./js/app.js"></script>
<body>
</body>
</html>
Output
To try examples, run http-server from project root:
$ http-server
Loading index.html in browser will print following in console:
2.7021706202022813
3
123
available function from lib2: getCubicRoot(x)
Example ProjectDependencies and Technologies Used: - Node.js v8.11.3
- Google Chrome Browser Version 70.0.3538.102 (Official Build) (64-bit)
|