Dave Pile Dave Pile - 4 months ago 48
Javascript Question

Browserify, how to access main.js functions

I can get browserify working but am a little confused about how to access the functions in bundle.js from the DOM.

I have three files-


module.exports = function (){
return "Hello";


var getMessage = require('./message');

//This shows the alert when script loads

//cannot find this function from index.html
function fnClick(){


<!DOCTYPE html>
<script src="js/bundle.js"></script>
<button onclick="fnClick();">Click</button>

In the browser when the script loads
in main.js shows the alert but debugger, fnClick is undefined and I can work the scope.



Any code in entry file is executed in the closure. If you look at the created bundle.js, you will see something like this in there.

function(require, module, exports) {
    function fnClick() {

Anything you create in here will be just hidden to global space unless you explicitly use window object (but don't do that) to expose it.

As @elclanrs said in comments above, just attach even listener in your code instead of HTML. If you don't want to use external libraries, you can do it hard way.

var button = document.getElementById('my-button'); // add id="my-button" into html
button.addEventListener('click', fnClick);

Or with library like popular jQuery you would just call.