My First ES6 Test Code - Trying Modules without compilers (Export, Import)

With the basic knowledge of Javascript & jQuery, I decided to step in to ES6. What excites me is the Module where I can import & export multiple JS files. Currently its hard to manage when there are lot of functions in one JS file which I used to do using jQuery.

Since all modern browser now supports ES6, I decided not to compile and see how it runs in the browser.

I started with a basic HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hi</h1>
    <script src="./main.js" type="module"></script>
</body>
</html>

Then I created 3 modules and one main.js to include in my HTML Page.

a.js

import { stuff } from "./b.js";
import { randhex, validURL } from "./c.js";

stuff("It works");

console.log(import.meta); 
console.log(validURL("google.com/")); 
const goolink = validURL("google.com/");

console.log(randhex(5)); 

export { validURL, goolink };

b.js

const stuff = function (text) {
  console.log(text);
};

export { stuff };

c.js

const validURL = function (str) {
  var pattern = new RegExp(
    "^(https?:\\/\\/)?" + // protocol
    "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
    "((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
    "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
    "(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
      "(\\#[-a-z\\d_]*)?$",
    "i"
  ); // fragment locator
  return !!pattern.test(str);
};

const randhex = function (len) {
  var maxlen = 8,
    min = Math.pow(16, Math.min(len, maxlen) - 1),
    max = Math.pow(16, Math.min(len, maxlen)) - 1,
    n = Math.floor(Math.random() * (max - min + 1)) + min,
    r = n.toString(16);
  while (r.length < len) {
    r = r + randHex(len - maxlen);
  }
  return r;
};
export { randhex, validURL };

main.js

import { goolink } from "./a.js";

if (goolink) {
  console.log("yaay");
}

Result

Here's what I got in console.log It works and runs in the browser without any issues. No compilers, No Babel, No Webpack nothing. Just pure Javascript.

It works
> Object
true
yaay

What I learned

  1. ES6 Modules will only work on a Server like localhost or web server. It won't work via file:///
  2. While adding <script> tag to HTML, we must add type="module" attribute. Otherwise the module won't work.

Your Suggestions

Do you have any suggestions on how to improve my code? or any other stuff I should be aware of? Let me know in the comments.

Did you find this article valuable?

Support Surjith's Blog by becoming a sponsor. Any amount is appreciated!