Gulp + Browserify + Babelify意外令牌

时间:2016-02-23 04:47:57

标签: reactjs gulp syntax-error browserify babeljs

我使用Gulp使用Browserify和Babelify转换jsx / es6但我收到错误:Unexpected token (7:12) while parsing file: app.jsx 我究竟做错了什么?我可以

app.jsx (7:12为<div>

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

class App extends React.Component{
    render() {
        return (
            <div>
                <Header />
                <div className="container">
                    {this.props.children}
                </div>
            </div>
        );
    }
}

export default App;

gulpfile.js

var bundler = watchify(browserify({
    entries: './client/components/app.jsx',
    transform: [babelify],
    extensions: ['.jsx'],
    debug: true,
    cache: {},
    packageCache: {},
    fullPaths: true
}));

function bundle(file) {
    if (file) gutil.log('Recompiling' + file);
    return bundler
        .bundle()
        .on('error', gutil.log.bind(gutil, "Browserify Error"))
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./client/scripts'))
}
bundler.on('update', bundle);

gulp.task('build', function() {
    bundle()
});

在我的package.json中我有:

"browserify": {
    "transform": [["babelify", {"presets": ["es2015"]}]]
  }

更新

gulp.task('build', function () {
    gulp.src('./client/components/app.jsx')
        .pipe(browserify({
            extensions: ['.jsx'],
            debug: true,
            cache: {},
            packageCache: {},
            fullPaths: true
        }))
        .pipe(babelify({presets: ['es2015', 'react']}))
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./client/scripts/'))
});

我更改了gulp任务,但现在我收到了错误:

Browserify Error [TypeError: Invalid non-string/buffer chunk]

2 个答案:

答案 0 :(得分:1)

您目前尚未将jsx转换为普通Javascript。

Browserify配置中,您应该有react预设来实现此目的。对你而言,这将是:

"browserify": {
    "transform": [["babelify", {"presets": ["es2015", "react"]}]]
}

您还需要安装此预设。 npm install babel-preset-react

More information about presets

More information about react preset

答案 1 :(得分:0)

我遇到了同样的错误,在我的情况下,升级节点仅解决了问题。