Modules in JavaScript confusion

I am simply trying to execute below javascript code ,involving the concept of module but getting unexpected error .

I am referring modules in javascript of code academy and in codecademy platform , code is running successfully .

// index.html

<!doctype html>

<html>
    <head>
        <title>Page Title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="initial-scale=1.0">
    </head>

    <body>

<script src="abc.js"></script>
<script src="abcd.js"></script>

    </body>
</html>

// abc.js

let Airplane = {};

Airplane.myAirplane = "StarJet";

module.exports = Airplane;


// abcd.js 

const Airplane = require('./abc.js');

function displayAirplane() {
  console.log(Airplane.myAirplane);
}

displayAirplane();

Comments (3)

Ibrahim Tanyalcin's photo

Thats not meant to be run on client side. For commonJS, check for instance rollup or Browserify.

<shamelessPromotion>

But, I have thought about this bundler issue for an enterprise project that has to work ie10+. I wanted to support latest ES6 stuff like promises but also fallback to rAF if necessary without any transpilation + build time. You can run this script like this:

//abc.js
!function(){
    var abc = function()
        let airPlane = {};
        airPlane.myAirPlane = "StarJet";
        taskq.export(airPlane,"airPlane");//export it airPlane with a alias
    };
    abc._taskqId = "abc"; //give it an id
    taskq.push(abc);//push to queue, it will be automatically executed when conditions are right
}();
//abcd.js
!function(){
    var abcd = function(airPlane){
        function displayAirplane(){
            console.log(airPlane.myAirPlane);
        };
        displayAirplane();
    }
    abcd._taskqId = "abcd";
    abcd_taskqWaitFor = ["abc"]; /*an array of ids that this function should wait before it executes*/
    taskq.push(abcd);
}();

then in your html:

....
<script src="abc.js" async></script>
<script src="abcd.js" async></script>
....

The above order of scripts does NOT matter, put them anywhere you like.

</shamelessPromotion>

Check for taskq in npm or in my github. I have a new version which takes a bit longer to sort the dependency tree (~1ms, but more stable), I will upload it soon. You are also able to make dynamic imports that respects the queue order, which I will not explain here for clarity.

Matt Strom's photo

Unfortunately, modules (more precisely, CommonJS modules) are not natively available in the browser. You need to use another module systems such as RequireJS, SystemJS, Browserify, Webpack, or the Universal Module Definition (UMD) pattern to use modules in the browser.

Also unfortunately, those are not the easiest libraries to use.

Jason Knight's photo

The less code you use, the less there is to break

The "not natively available in browsers" being just part of why I've had little reason to even touch them.

That and it seems like a crutch for people who can't organize their code properly.