Close

JavaScript Modules - Empty Import for running global code

[Updated: Nov 30, 2018, Created: Nov 28, 2018]

We can use following syntax to run the target module's global code without importing anything:

import "<module-name>"

Example

js/lib.js

console.log("loading lib");

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

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

js/app.js

import "./lib.js";

console.log("app running");
showSum(3, 5);//error because it is not imported

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

On loading index.html, following is printed in console:


Example Project

Dependencies and Technologies Used:

  • Node.js v8.11.3
  • Google Chrome Browser Version 70.0.3538.102 (Official Build) (64-bit)
JavaScript Modules - Empty Imports Select All Download
  • javascript-empty-import
    • js
      • app.js

    See Also