1

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?

0

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

3 Comments

It looks like he's just creating the Parent in the global scope of the module, meaning it will probably run whenever it is required. This still makes it a scope issue, but maybe with a different solution.
@shennan It's in a separate module. Browserify bundles separate modules using CommonJS format. So the module has to be exported and imported using those semantics.
Yes exactly, you're unedited question did not include the export code. Now it does. I commented before the edit. I'm pretty sure you saw it though. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.