Robert Strauch
Robert Strauch

Reputation: 12896

Function cannot be called in browser after browserify: Uncaught ReferenceError

I'm developing a small NPM package. This is a basic prototype:

function foo() {
  return 'foo';
}

module.exports = foo;

This module shall also be usable in a browser. So I installed browserify and ran this command:

browserify foo.js -o foo_bundle.js

Which gives me:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
function foo() {
  return 'foo';
}

module.exports = foo;
},{}]},{},[1]);

And a sample HTML document:

<html>
  <head>
    <script src="foo_bundle.js"></script>
  </head>
  <body>
    <div id="myElement"></div>
    <script type="text/javascript">
      var element = document.getElementById("myElement");
      element.innerHTML = foo();
    </script>    
  </body>
</html>

I would have expected the string foo being written to the div element but instead the JavaScript console of the browser prints:

foo.html:9 Uncaught ReferenceError: foo is not defined

What am I missing here?

Upvotes: 2

Views: 920

Answers (1)

kkkkkkk
kkkkkkk

Reputation: 7748

You need to bundle its as a standalone version (UMD) to use in browser:

browserify foo.js -o foo_bundle.js -s foo

More usage here

Upvotes: 4

Related Questions