2

I am trying to learn browserify to manage my javascript. My first simple task is to create a react.js file which will be generated by gulp + browserify

var browserify = require('gulp-browserify');

gulp.task('browserify-react', function () {
  return gulp.src('js/react/react.js')
  .pipe(browserify())
  .pipe(rename('react-generated.js'))
  .pipe(gulp.dest('./dist'));
});

In js/react/ I created a file react.js which is just two require commands:

var React = require('react');
var ReactDOM = require('react-dom');

I expect that a new file react-generated.js will content a react and react-dom modules.

File will be generated, but when I try to use this react-generated.js in my project I get two errors

ReferenceError: React is not defined
ReferenceError: ReactDOM is not defined

But if I use react javascript from facebook, so everything is ok, no errors

<script src="https://fb.me/react-0.14.0.min.js"></script>
<script src="https://fb.me/react-dom-0.14.0.min.js"></script>

Questions. What do I miss when I generate react components by using of gulp-browserify?

Kyeotic
  • 19,697
  • 10
  • 71
  • 128
podeig
  • 2,597
  • 8
  • 36
  • 60
  • Yes, I did it. File react-generated.js is generated. But why do I get the error? – podeig Nov 19 '15 at 22:41
  • Are you using browserify to package just react and react-dom? That isn't going to make them accessible outside of that package. You need to package your entire application – Kyeotic Nov 19 '15 at 22:44
  • Thank you, Tyrsius. I see. But what can I use in gulp just to get react components which are installed by npm? Just to pack them in one file and minimize them? – podeig Nov 19 '15 at 22:50
  • @podeig See pygeek's answer – Kyeotic Nov 20 '15 at 01:53
  • @podeig Was my answer sufficient? If so, you may want to mark it as the answer for others viewing this question. – pygeek Jan 24 '16 at 05:37
  • I've the same problem too. I see that the generated file brings both react and react-dom. But still have this error. – iroel Jan 27 '16 at 17:18

1 Answers1

2

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
}
pygeek
  • 7,356
  • 1
  • 20
  • 41
  • Here's a follow up: http://stackoverflow.com/questions/26672071/browserify-create-bundle-with-external-module – James Bowler Jan 23 '16 at 18:56
  • If this's little hack outside browserify, then it doesn't answer the question. – iroel Jan 27 '16 at 17:15
  • Browserify packages node.js for use in the browser allowing you to leverage other node modules. The method I'm describing is how you expose objects to other modules in node.js. It is not a hack. https://nodejs.org/api/modules.html – pygeek Jan 27 '16 at 17:22