Use of browserify to pack React components

2019-02-25 20:31发布

问题:

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?

回答1:

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
}