Skip to content

Instantly share code, notes, and snippets.

@yilmazdurmaz
Created May 26, 2023 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yilmazdurmaz/a51e93f291d6b8d801eb32c272d79dea to your computer and use it in GitHub Desktop.
Save yilmazdurmaz/a51e93f291d6b8d801eb32c272d79dea to your computer and use it in GitHub Desktop.
Use same Javascript module in both HTML and Node.js
#JS-Modules-in-HTML-and-Nodejs

Writing modern Javascript code for both HTML (or Web) and Node.js (or Stand-alone)

When writing for both, 3 things are important:

  • using type="module" in the HTML file
  • using "type": "module" in the package.json file (for Node.js)
  • and every import statement uses .js extension

typeof feature != "undefined" is used to check if a feature is available. Else, another method is used; for example console.log for alert.


files used:

  • index.html - for Web
  • index.js - entry point for both
  • package.json - for Node.js
  • main.js - not needed, extra layer
  • module.js - example module layer

to run with Node.js, just run node index.js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test JS module import</title>
</head>
<body>
<script src="main.js" type="module"></script>
<script src="module.js" type="module"></script>
<script src="index.js" type="module"></script>
</body>
</html>
import main from "./main.js";
main();
import hello from "./module.js";
let main = () => {
hello();
};
export default main;
let hello = () => {
if (typeof alert != "undefined") {
alert("hello world");
} else {
console.log("hello world");
}
};
export default hello;
{"type": "module"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment