【问题标题】:Syntax Error when using Gulp to compile React in ES6在 ES6 中使用 Gulp 编译 React 时出现语法错误
【发布时间】:2015-10-30 05:16:23
【问题描述】:

当我尝试使用 React 编译以下代码时,出现以下错误。我在这么简单的程序中看不到问题,并且当我克隆 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
);

你好世界:

import React from 'react';


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

export default HelloWorld;

错误:

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

【问题讨论】:

  • 你是怎么编译的?
  • 用 babelify 吞咽。如有必要,我可以发布 gulp dil​​e
  • 此时您如何配置babelify?如果您使用的是最新版本,则需要将 es2015react 作为两个单独的预设启用。
  • 我建议您切换到高级 webpack,除此之外,您似乎没有正确设置编译器来检测和编译 jsx
  • loganfsmyth 你是对的。这个要求似乎并没有在整个文档中体现出来。如果你愿意,你可以重新输入这个答案,我会接受的。

标签: javascript reactjs gulp ecmascript-6


【解决方案1】:

我在使用最新版本的 babelify、browserify 和 react 时遇到了这个问题。您需要为最新版本的 babelify 指定预设配置。一个 es6 gulp 任务可能看起来像这样:

'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));
});

请注意,正在向 browserify 传递一个配置对象,该对象包含用于包含 babelify 转换的转换属性,该转换也正在使用对象进行配置。 babelify 配置对象包含预设。您还应该 npm install 您希望使用的预设。您可以在https://github.com/babel/babelify#options 阅读更多相关信息。

我注意到的另一件事是您没有提及您的 Reactjs 版本。最新的是 0.14.2,它比 0.13.3 做了一些重大更改。使用最新版本,您还需要 react-dom 并将其用作组件到 DOM 的挂载点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2012-07-03
    • 2016-06-21
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多