简体   繁体   中英

Syntax Error when using Gulp to compile React in ES6

When I try to compile the following code using React I get the error below. I don't see the issue in such a simple program and the example code compiles correctly when I clone the git repo.

main.js:

import React from 'react';
import HelloWorld from './components/helloworld';
//import HelloWorld from './hello-world-es5';

React.render(
    <HelloWorld phrase="ES6"/>,
    document.body
);

HelloWorld:

import React from 'react';


class HelloWorld extends React.Component {
    render() {
        return <h1>Hello from {this.props.phrase}!</h1>;
    }
}

export default HelloWorld;

error:

SyntaxError: /Users/**/**/**/**/js/main.js: Unexpected token (7:4)
  5 | 
  6 | ReactDOM.render(
> 7 |     <HelloWorld phrase="ES6"/>,
    |     ^
  8 |     document.body
  9 | );
    at Parser.pp.raise 
Process finished with exit code 1

I ran into this problem while using the latest versions of babelify, browserify, and react. You need to specify a presets configuration for the latest versions of babelify. An es6 gulp task might look something like this:

'use strict';

import browserify from 'browserify';

import babelify from 'babelify';
import reactPreset from 'babel-preset-react';
import es2015Preset from 'babel-preset-es2015';

import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';

import gulp from 'gulp';
import gutil from 'gulp-util';
import uglify from 'gulp-uglify';
import sourcemaps from 'gulp-sourcemaps';

import config from '../config'; //externalized json config file

gulp.task('compile', function () {
    var b = browserify({
        entries: config.entries,
        debug: true,
        transform: [babelify.configure({'presets': [reactPreset, es2015Preset]})]
    });

    return b.bundle()
        .pipe(source(config.source))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .on('error', gutil.log)
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(config.dest));
});

Note that the browserify is being passed a configuration object that contains the transform property for containing the babelify transform that is also being configured with a object. The babelify configuration object contains the presets. You should also npm install the presets that you wish to use. You can read more about this at https://github.com/babel/babelify#options .

One other thing that I noticed is that you don't mention your Reactjs version. The latest is 0.14.2 which made some significant changes over 0.13.3. Using the latest you would also need react-dom and use that as the mount point for your component to the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM