Search code examples
reactjsgulpbrowserifywatchifyreactify

Browserify transform with reactify


I am trying to build a project using gulp. Unfortunately I am experiencing some trouble with it.

This is what my gulpfile.js looks like:

'use strict';

var watchify = require('watchify');
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');
var reactify = require('reactify');

// add custom browserify options here
var customOpts = {
  entries: ['./js/app.js'],
  debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts)); 
b.transform(reactify);

// add transformations here
// i.e. b.transform(coffeeify);

gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {

  return b.bundle()
    // log errors if they happen
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    // optional, remove if you don't need to buffer file contents
    .pipe(buffer())
    // optional, remove if you dont want sourcemaps
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
       // Add transformation tasks to the pipeline here.
    .pipe(sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./js/build'));
}

The problem is that gulp is displaying an error indicating that some third party library has somewhere the illegal token '<' the file in question is written in the JSX syntax.

Yet, I don't have the problem when I run the following command:

browserify -g reactify js\app.js > js\build\bundle.js

Please, what is wrong with my gulpfile?

Thanks in advance to anybody seeking to help!

Edit: I suspect that the -g option makes it transform the jsx recursively to plain javascript, I'm trying to find out an equivalent in the watchify.transform function, unsuccessfully.


Solution

  • As the docs for .transform say:

    If opts.global is true, the transform will operate on ALL files, despite whether they exist up a level in a node_modules/ directory

    So to replicate -g reactify, you'd do

    b.transform(reactify, {global: true});
    

    Keep in mind however that I would consider the fact that you need -g to be a bug in whatever dependency node_module you are referring to. Generally modules should include browserify config params in their own package.json file so that you don't have to configure it globally. As the next part of those docs say:

    Use global transforms cautiously and sparingly, since most of the time an ordinary transform will suffice.