在Cordova中加载带有require的模块

问题描述:

我是javascript尝试使用模块require()的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.

这是我的html代码。

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>

这是我的greeting.js的代码

This is the code for my greeting.js

  //var exports = module.exports = {};

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

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

当我点击按钮点击时,它会给出一个错误,即abc未定义。我在这里缺少使用该模块的东西吗?
非常感谢。

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.

实际上 module.require 不适用于浏览器。你不能像在脚本 -tag中那样使用它。 require 适用于node.js(服务器端javascript)。

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).

如果你想在里面使用它浏览器你应该使用预处理。例如,您可以使用 browserify

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

要了解更多信息 - 很棒的3分钟视频 CommonJS模块

To learn more - great 3 min video CommonJS modules