Following are different ways of exporting features:
Inline Named Export Declaration export function doSomething1() {.....}
export function doSomething2(){....} This is what we have been doing in previous tutorials.
Separate export clause with variable statement export {doSomething1, doSomething2}
function doSomething1() {.....}
function doSomething2(){....}
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(){....}
Default export export default function doSomethingByDefault(){.....}
Check out tutorial here
Example
js/lib.jsexport 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.jsexport {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.jsimport 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 ProjectDependencies and Technologies Used: - Node.js v8.11.3
- Google Chrome Browser Version 70.0.3538.102 (Official Build) (64-bit)
|