简体   繁体   English

在Electron中需要和扩展类,怎么办?

[英]Require and extend classes in Electron, how to?

I have a file global.js that contains 我有一个文件global.js包含

var Global = (function () {
    function Global() {
        this.greeting = 'test';
    }

    Global.prototype.getList = function () {
        return "Hello, " + this.greeting;
    };
    return Global;
})();

and another file 'main.js', that contains 还有另一个文件“ main.js”,其中包含

var global= new Global();

console.log(global.getList);

then i require them in the index.html 然后我在index.html中要求它们

...
<script>
    require('./npmMain.js');
    require('./main.js');
</script>

and i get Global is not defined Global is not defined

How can i make the class available to main.js? 我如何使该类可用于main.js?

Any ideas? 有任何想法吗?

edit: if i console.log('test'); 编辑:如果我console.log('test'); inside npmMain.js i can see it run, so the file is getting required, just that class is not available or something npmMain.js里面,我可以看到它正在运行,因此该文件变得必需了,只是该类不可用或其他原因

Welcome to the world of modules! 欢迎来到模块世界!

First, inside of your main.js file, add a line at the top like this: 首先,在main.js文件中,在顶部添加一行,如下所示:

var Global = require('./npmMain.js').Global;

Then at the end of npmMain.js add a line like this: 然后在npmMain.js的末尾添加如下一行:

exports.Global = Global;

Then remove that line from index.html . 然后从index.html删除该行。 That should do it. 那应该做。

I am guessing that you are not familiar with CommonJS style modules. 我猜您对CommonJS样式模块不熟悉。 Modules do not share global variables. 模块不共享全局变量。 Everything (except for a few properties supplied by the commonJS implementation) needs to be required before it can be used. 在使用之前,需要所有内容(由commonJS实现提供的一些属性除外)。 Also, if you want to expose values between modules, you need to use exports keyword. 另外,如果要在模块之间公开值,则需要使用exports关键字。

There is a much more detailed explanation on the CommonJS site . CommonJS网站上有更详细的解释。

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

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