简体   繁体   中英

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.

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

You cannot use require / module.exports natively in the browser. It is built into Node.js/io.js and can be run on the server.

If you want to use require() /CommonJS modules in the browser, look at RequireJS .

If you want to run Node/io.js code in the browser in general (including but not limited to require() /CommonJS), look at Browserify or webpack .

Since you say you are using cordova, my guess is that you don't really need require() at all. Just write your HTML/CSS/JavaScript like you would normally and use cordova to package it up. cordova uses require() a lot but that should not affect your app's code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM