简体   繁体   中英

Require and extend classes in Electron, how to?

I have a file global.js that contains

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

var global= new Global();

console.log(global.getList);

then i require them in the index.html

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

and i get Global is not defined

How can i make the class available to main.js?

Any ideas?

edit: if i 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

Welcome to the world of modules!

First, inside of your main.js file, add a line at the top like this:

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

Then at the end of npmMain.js add a line like this:

exports.Global = Global;

Then remove that line from index.html . That should do it.

I am guessing that you are not familiar with CommonJS style modules. 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. Also, if you want to expose values between modules, you need to use exports keyword.

There is a much more detailed explanation on the CommonJS site .

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