Toni Leigh
Toni Leigh

Reputation: 4971

Gulp with React not compiling a functional component correctly

I have the following gulpfile.js:

var gulp = require('gulp'),
    babel = require('gulp-babel'),
    concat = require('gulp-concat'),
    react = require('gulp-react'),
    sass = require('gulp-sass'),

    jsxToJs = function() {
      //gulp.src('src/**/*.js')
      gulp.src('./src/sections/header/header.js')
        .pipe(react())
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(concat('javascript.js'))
        .pipe(gulp.dest('./'));
    };

gulp.task('jsxToJs', jsxToJs);
gulp.task('build', ['jsxToJs', 'styles']);

gulp.task('watch', function () {
    gulp.watch([
        './src/**/*.js', 
        './src/**/*.scss'
    ], [
        'jsxToJs', 
        'styles'
    ]);
});

gulp.task('default', ['build', 'watch']);

And I'm trying to compile the following functional React component:

let Header = (props) => {
  return(
    <div />
  );
};

However, when I run the javascript.js file created by gulp I get the following error:

Uncaught TypeError: e.render is not a function

If I convert the component back to the old way of doing things like this (which is how I found it as I'm revisiting an old problem):

var Header = React.createClass({
  render: function() {  
  }
});

Then it works.

Looking at the compiled JS shows me this - where I can see that render is being compiled out correctly with the old syntax, but for the new syntax, while it's being ESfivified it's not being reactified:

// not working
"use strict";

var Header = function Header(props) {
  return React.createElement("div", );
};

// working
"use strict";

var Header = React.createClass({ displayName: "Header",
  render: function render() {
    return React.createElement("div", );
  }
});

I've checked that I've installed my gulp requires correctly and I'm using Node 6.10.2. My gulp file has some extra things for scss in that I've removed for this question.

A couple of other points:

Can anyone explain what I'm doing wrong?

Upvotes: 1

Views: 474

Answers (1)

Toni Leigh
Toni Leigh

Reputation: 4971

The solution turned out to be pretty simple.

Babel requires presets to be provided in order to transpile.

I had the es2015 preset, but not the react one. Therefore react specific tranpilations were not occurring. This addition fixed the problem:

.pipe(react())
.pipe(babel({
    presets: ['es2015', 'react']
}))

The mistake I was making, that sent me down the wrong rabbit hole in Google, was assuming that failing to reactify was something to do with the gulp-react function - silly me.

Upvotes: 1

Related Questions