Reputation: 27058
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
Upvotes: 3
Views: 3574
Reputation: 28757
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.
Upvotes: 4