Javascript - Module

Subscribe Send me a message home page


Related Reading

Use JavaScript file as a module

The JavaScript module is similar to Python module. It makes code reuse easier. To use a JavaScript script file as a module, we need to specify the type of script tag:

1
<script type="module" src="<path-to-js-file>"></script>

Import and Export

To reuse code in another JavaScript file, we could import content from that file. There are different syntax for import:

1
2
3
4
5
6
7
8
9
10
11
import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
var promise = import("module-name");

The syntax at line 2 is particularly interesting: it allows us to define a namespace. For example, suppose we define a getCurrentTime() function in utils.js file. Now in the main.js we can import the getCurrentTime() function and put it in the myutils namespace.

1
2
3
4
5
6
7
8
9
10
// utils.js
function getCurrentTime() {
    return Date.now();
}

export {getCurrentTime};

// main.js
import * as myutils from "./utils.js";
myutils.getCurrentTime();

Unlike Python, in order to make a function visible to other modules we need to explicitly export the function. For example, in the above code at line 6, we export the getCurrentTime() function in the utils.js script.

How to access functions of a module in html file?

Notice that import and export can only be used in a module so in order to access a function defined in a module inside a html file, the first step is to create a module script tag. What about the part in the html file which is outside the module script tag? They don't belong to any JavaScript module!

The workaround is to register the function in the window namespace. Here is the code

1
2
3
4
5
6
7
8
9
<!-- main.html -->

<script type="module">
    import {getCurrentTime} from "./utils.js";
    window.getCurrentTime = getCurrentTime;
</script>

<div id="get-current-time" onclick="getCurrentTime">
</div>

----- END -----

Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png


Comments