javascriptbrowserifyreactify

Browserify/Reactify - Uncaught ReferenceError: function is not defined


I'm trying to abstract my code and I have the following two files in the following structure

main.js
  components
  - parent.js

main.js

require('./components/Parent');

ReactDOM.render(
    <Parent />,
    document.getElementById('content')
);

components/Parent.js

var Parent = React.createClass({
  displayName: 'Parent',
  render: function(){
    return (
      <div>
        <div> This is the parent page. </div>
      </div>
    )
  }
});

index.html

<div id="app">  
</div>

I run the following -

browserify -t reactify main.js -o main_js.js

And this is the javascript it creates

(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){
require('./components/Parent');

ReactDOM.render(
    React.createElement(Parent, null),
    document.getElementById('content')
);

},{"./components/Parent":2}],2:[function(require,module,exports){
var Parent = React.createClass({
  displayName: 'Parent',
  render: function(){
    return (
      React.createElement("div", null, 
        React.createElement("div", null, " This is the parent page. ")
      )
    )
  }
});

},{}]},{},[1]);

Running the page complains on line 5 which is React.createElement(Parent, null),

Uncaught ReferenceError: Parent is not defined

But as you can see the file is loaded, so why is it not finding it in the file?


Solution

  • Change require('./components/Parent'); to var Parent = require('./components/Parent');

    You need to specify the name of the variable it's assigned to. Also, if you're placing them in different modules, you need to export the module.

    // in ./components/Parent
    module.exports = Parent;