Search code examples
javascriptreactjsgulpbrowserifybabeljs

React JavaScript with ES6 compiling issue under browserify and babel


I am trying to create a basic React component with the recently introduced ES6 syntax.

My current file schema looks like this: I have a root feed.jsx file which SHOULD import React and my custom components

import React from 'react';
import ReactDOM from 'react-dom';
import FeedApp from './components/FeedApp';

var target = document.getElementById('FeedApp');
ReactDOM.render(FeedApp, target);

My FeedApp, which imports another component, looks like this:

import React from 'react';
import Header from './Header';

class FeedApp extends React.Component{
  constructor(){
    this.state = {
      customHeading: "Hello"
    }
  }
  render() {
    return (
        <div className="clearfix wrapper">
          <Header />
        </div>
    );
  }
}

export default FeedApp;

The imported Header component is also a basic one:

import React from 'react';

class Header extends React.Component {
  render() {
    return(
      <div className="top-bar">
        <div className="top-logo-wrapper">
          <a href="/" title="Homepage">
            <img src="/imgs/logo-b.png" alt="Logo" />
          </a>
          <a href="/" title="Homepage">
            <h1>Title</h1>
          </a>
        </div>
      </div>
    );
  }
}

export default Header;

And last but not least my gulpfile content, which should compile everything into one file:

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

gulp.task('build', function () {
  browserify({
    entries: 'public/js/build/feed.jsx',
    extensions: ['.jsx'],
    debug: true
  })
  .transform(babelify)
  .bundle()
  .pipe(source('public/js/build/bundle.js'))
  .pipe(gulp.dest('dist'));
});

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

Right after running the gulpfile I get the following output:

[12:15:49] Working directory changed to /path/folder
[12:15:49] Using gulpfile /path/folder/gulpfile.js
[12:15:49] Starting 'build'...
[12:15:49] Finished 'build' after 22 ms
[12:15:49] Starting 'default'...
[12:15:49] Finished 'default' after 7.46 μs

events.js:141
      throw er; // Unhandled 'error' event
      ^
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'

I have read that this might be a babel issue since it doesn't provide any "addons" automatically any more. If it is so - would anyone be so kind and help me edit my gulpfile.js (or other file) so that I have everything set up to use the glories of ES6 and react ?

Thank you :)


Solution

  • Or npm install --save-dev babel-preset-es2015 babel-preset-react and;

    .transform(babelify, {
      presets:["es2015", "react"]
    })