Ad

Using Browserify To Create React Bundle

- 1 answer

It's the same question as here, but I don't understand the answer. So, my question is about the answer.

The answer is

Your react.js file/module isn't exposing the variables React and ReactDOM you instantiate. In node, you make these methods public by modifying the module.exports object like so:

module.exports = { React: React, ReactDOM: ReactDOM }

Finally, my question is: Where do "you make these methods public"?

Ad

Answer

You are making these methods public by defining them on the module.exports property. For instance, say you have a file reactExports.js with

var iWontGetThere = 'I am in this module only';
module.exports = { React: React, ReactDOM: ReactDOM } 

now in another file, you can require these methods and use them, like so:

var React = require('reactExports').React;
var SweetComponent = React.createClass({
   render: function() {
     return (
        <div>React is cool and I can use it in here!</div>
     );
   }
});
module.exports = SweetComponent;

Now imagine you want to render SweetComponent in another component. If I hadn't written module.exports = SweetComponent, requiring this module in another component would have no effect as all as you would be importing an empty object {}. Let's say I tried to console.log(React.iWontGetThere); What would happen? I would get a reference error, as it was not exported with the contents of reactExports.js-it only exists in that module, but it is not exposed.

This is a contrived example, but the interesting story here is the ability to bring in encapsulated modules. I suggest reading more about node modules here and checking out this answer as well. and making some examples to get the hang of it.

tl;dr: defining variables and not having a module.exports = some_value statement then requiring that same file will default to an empty object.

Ad
source: stackoverflow.com
Ad