Stas Makarov Stas Makarov - 5 months ago 79
Javascript Question

gulp + browserify + reactjs, Uncaught ReferenceError: React is not defined

I'm trying to follow workflow suggested in this file: https://gist.github.com/nateajohnson/4d16df279d2e3d2b6b16 , so that in the end I get two separate .js files: one for vendor libs and the other for my own code.

My Gulpfile.js:

var gulp = require('gulp'),
// ... there shouldn't be any problems

gulp.task('build-vendor', function() {
var b = browserify({ debug: false});

b.require(nodeResolve.sync('jquery'), { expose: 'jquery' });
b.require(nodeResolve.sync('react'), { expose: 'react' });
b.require(nodeResolve.sync('react/addons'), { expose: 'react/addons' });
b.require(nodeResolve.sync('react-select'), { expose: 'react-select' });

var stream = b.bundle()
.pipe(source('vendor.js'))
.pipe(gulp.dest('assets/build/js'))
.pipe(buffer())
.pipe(uglify())
.pipe(rename('vendor.min.js'))
.pipe(gulp.dest('assets/build/js'))
.pipe(gzip())
.pipe(gulp.dest('assets/build/js'));

return stream;
}) ;


gulp.task('build-app', function() {

var b = browserify('assets/dev/js/app.js', { debug: false });

b.external('jquery');
b.external('react');
b.external('react-select');

var stream = b.transform(babelify, { stage: 0 })
.bundle()
.on('error', function(e){
console.log(e.message);
this.emit('end');
})
.pipe(source('bundle.js'))
.pipe(gulp.dest('assets/build/js'));

return stream;
});


When I'm trying to use React variable in my own code, I get the error:


Uncaught ReferenceError: React is not defined


I can get rid of this either by including

var React = require('react');


in each of my js files which use react,
or by including

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


in my HTML (which obviously not very good solution).

Just in case, I pushed this project on github: https://github.com/jehaby/ireact/tree/master/kindle

So my questions is why do I get this error and how to solve it the right way ( I'm sure there is some )? I believe it might be stupid questions, but I'm new to this tools. I've already spent several hours trying to figure out what's wrong and now feel kinda stuck. Will be very grateful for any help.

Answer

With browserify and babelify you should declare your dependencies in each file:

//node's style
var React = require('react')
// ES 2015 modules
import React from 'react';

Take a look on available examples how to work with ES2015 modules and React:

https://github.com/lukehoban/es6features#modules

https://github.com/erikras/react-redux-universal-hot-example/blob/master/src%2Fcomponents%2FCounterButton.js

Comments