1

I have a NodeJS file which I browserfied using browserify module. I used following command

browserify testFile.js -o bundle.js 

To make use of this file in browser, I am making use of window object.

Assume below code is generated after browserifying the file.

var Main = function () { this.foo = function () { }, this.temp= function () { }, this.bar= function () { } } 

to make use I changed it to

window.Main = function () { this.foo = function () { }, this.temp= function () { }, this.bar= function () { } } 

and then to use of these functions, I used following code:

var obj= new Main (); 

and then I can say obj.foo(); or obj.bar();

All this is working fine but I wonder if this is the right way to call function from a browserfied file.

Please suggest correct way to make use of browserfied file.

1 Answer 1

1

Browserify is a great tool when you use it for the entire project. It makes almost no sense to use it for single files only. The whole point of it is avoiding globals, instead of setting window.Main you could do this:

module.exports = function () { this.foo = function () { }, this.temp= function () { }, this.bar= function () { } } 

And then in all files that need access to the above, do:

var Main = require('./path/to/main.js'); 

Browserify resolves and inlines all require calls automatically so you only need to run Browserify on the single file that fires up the app.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. I am little confused though. Consider the Main() which I have shown, internally makes call to various other function(spanning across multiple file). I have included all these files in testFile.js (which contains main() & which I will browserify) using require. My question is once I browserify the file, How can I call functions from this file from another JavaScript file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.