Search code examples
javascriptnode.jscordova

Loading modules with require in Cordova


I am new to javascript trying out cordova which heavily makes use of the module require(). I went through some tutorials for this like here . I tried out a very simple example from this tutorial and there is something missing it seems.

This is my html code.

 <script>
 var abc = require("js/greeting.js");
        function mod() {
            try{
                
                var g =  abc.sayHelloInEnglish();
            console.log("reached the call");
            document.getElementById("modl").innerHTML = g;
            }
            catch(err){
                console.log("error is" + err.message);
            }   
        }
    </script>
    <button onclick="mod()">click</button>

This is the code for my greeting.js

  //var exports = module.exports = {};
     
exports.sayHelloInEnglish = function() {
    return "HELLO";
};

exports.sayHelloInSpanish = function() {
    return "Hola";
};

When I click on the button click, it gives an error that abc is not defined. Is there something I am missing here to use the module? Thanks a lot.


Solution

  • Actually module.require is not for browser. You can't use it like you do right inside script-tag. The require is for node.js (server-side javascript).

    If you want to use it inside a browser you should use preprocessing. For example you can use browserify.

    To learn more - great 3 min video CommonJS modules