JS: require in addons? (IDE 9)

In this wiki page I see that addons can require custom js files.
Let’s imagine the situation:
In file “mycooljs.js” in folder content/js/ I have this code:

 var myobj = {
    name: "test",
    func: function () {
        return name in this;
    }
}

And in chrome.manifest I insert this line:

category require-path mycooljs chrome://myaddon/content/js/

And in another js file (e.g. “myanothercooljsfile.js”) I try to require mycooljs:

var mycooljs = require("myaddon/mycooljs");

And what I get in mycooljs variable? Can I get access to object myobj in mycooljs.js via mycooljs.myobj?

You have to tell commonjs require what you want to expose, eg. by setting module.exports = myobj.

Sample usage:

// Module
 var myobj = {
    name: "test",
    func: function () {
        return name in this;
    }
 }

module.exports = myobj;

// Usage
require('myaddon/mycooljs').func();
1 Like

Okay, but if I have more that 1 object? E.g.

var myobj = {
    name: "test",
    func: function () {
        return name in this;
    }
 }
var myobj2 = {
    callback: false,
    callback_func: function callback_func(callback, statement) {
        //code
    }
 }

I must write module.exports = myobj; module.exports = myobj2; or module.exports = {myobj, myobj2}; or module.exports = [myobj, myobj2]?

module.exports = {
   myobj: ...
   myobj2: ...
}
```

or 

```
var myobj = {};
var myobj2 = {};
module.exports = {myobj: myobj, myobj2: myobj2};
```

Basically you can do whatever you want, just make sure that any data you want to expose is in module.exports
1 Like

Last question: if in object I have functions with the same name - what will be do commonjs with this?

Keys must be unique to the parent object. You will have to structure your object properly.

Okay. Thanks, Naatan!

Stop stop stop…
category require-pathmycooljs chrome://myaddon/content/js/
In folder content/js:

  • test.js
    var mycooljs = require("myaddon/mycooljs");
    I think it must look like
    var mycooljs = require("mycooljs/test");
    Or not?

Yes, but you know you can just try it and see if it works, you do not need to ask for confirmation each time … I’m not a human linter :wink:

Be sure to install the Komodo Extension Developer addon, which will allow you to quickly test your module through the Javascript Shell.

Who is it? Google Translate can’t translate this word in Russian.

Linter, it’s what tells you whether you have errors in your code