简体   繁体   English

在Cordova中加载带有require的模块

[英]Loading modules with require in Cordova

I am new to javascript trying out cordova which heavily makes use of the module require(). 我是新手javascript尝试使用模块require()大量使用cordova。 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. 这是我的HTML代码。

 <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 这是我的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. 当我单击按钮单击时,它会给出一个错误,即未定义abc。 Is there something I am missing here to use the module? 我在这里缺少使用该模块的东西吗? Thanks a lot. 非常感谢。

Actually module.require is not for browser. 实际上module.require不适用于浏览器。 You can't use it like you do right inside script -tag. 你不能像在script -tag中那样使用它。 The require is for node.js (server-side javascript). require是node.js(服务器端javascript)。

If you want to use it inside a browser you should use preprocessing. 如果要在浏览器中使用它,则应使用预处理。 For example you can use browserify . 例如,您可以使用browserify

To learn more - great 3 min video CommonJS modules 了解更多 - 3分钟视频CommonJS模块

You cannot use require / module.exports natively in the browser. 您不能在浏览器中本机使用require / module.exports It is built into Node.js/io.js and can be run on the server. 它内置于Node.js / io.js中,可以在服务器上运行。

If you want to use require() /CommonJS modules in the browser, look at RequireJS . 如果要在浏览器中使用require() / CommonJS模块,请查看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 . 如果您想在浏览器中运行Node / io.js代码(包括但不限于require() / CommonJS),请查看Browserifywebpack

Since you say you are using cordova, my guess is that you don't really need require() at all. 既然你说你使用的是cordova,我的猜测就是你根本不需要require() Just write your HTML/CSS/JavaScript like you would normally and use cordova to package it up. 只需像平常一样编写HTML / CSS / JavaScript,然后使用cordova将其打包。 cordova uses require() a lot but that should not affect your app's code. cordova使用require()很多但不应该影响你的应用程序的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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