javascriptbrowserifyrequire

Cannot call module's function after browserify


I'm trying to make simple page with JS module that will do something with the page. I need to use node.js's modules so I'm learning how to browserify works.

My HTML:

<!doctype html>
<html>
    <head>
        <script src="js/bundle.js" type="text/javascript"></script>
    </head>
    <body>
        <p>Hello world!</p>
    <script type="text/javascript">
        var test = require("./test.js");
        test.init();
    </script>
    </body>
</html>

This is my JavaScript (test.js):

"use strict";

alert("here1");

var init = function() {
    alert("here2");
}

exports.init = init

I'm making a bundle with:

browserify.cmd test.js -o bundle.js

When I'm trying to open the page it shows "here1" but doesn't show "here2". In browser's console I see:

Uncaught ReferenceError: require is not defined      index.html:9

Any ideas how to make module's function (init) work well?


Solution

  • You need to put all JavaScript code which contains anything from Node in the test.js file which you are then converting with the browserify into te bundle.js. In your example you are using a Node function require in the index.html which is not going to be converted. Browser then sees function require() which he doesn't know and this is where the problem is hidden.

    Simply told: all your javascript code (containing Node) must be included in your index.html as a single bundle.js which is a browserifed result from your source files.

    EDIT

    Browserify doesn't (by default) allow you to call any browserified function out of the browserified code. But you can make it available by attaching the function into window scope.

    This is test.js (which is then converted to bundle.js by browserify) and index.html

    "use strict";
    
    alert("here1");
    
    window.init = function() {
      alert("here2");
    }
    <!doctype html>
    <html>
    
    <head>
      <script src="js/bundle.js" type="text/javascript"></script>
    </head>
    
    <body>
      <p>Hello world!</p>
      <script type="text/javascript">
    	init();
      </script>
    </body>
    
    </html>