Gulp + babelify + browserify问题

时间:2015-10-17 14:26:43

标签: javascript gulp browserify babeljs

我正在尝试使用browserify和babelify创建一个gulp任务。这是任务:

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

gulp.task('js', function () {
    browserify('./resources/js/*.js')
        .transform(babelify)
        .bundle()
        .pipe(source('*.js'))
        .pipe(gulp.dest('./public/js'));
});

我找到了一些示例代码,尝试使用它们,但结果总是一样。

当我运行任务并保存我的example.js文件时,会发生以下错误:

TypeError: browserify(...).transform is not a function

我做错了什么?

1 个答案:

答案 0 :(得分:14)

您正在混合使用browserifygulp-browserify

的API

gulp-browserify docs开始,您需要执行以下操作:

var gulp = require('gulp')
var browserify = require('gulp-browserify')

gulp.task('js', function () {
  gulp.src('./resources/js/*.js')
    .pipe(browserify({
      transform: ['babelify'],
    }))
    .pipe(gulp.dest('./public/js'))
});

编辑:由于首先回答了这个问题,gulp-browserify has been abandoned和gulp已经发展了很多。如果您想使用较新版本的gulp实现相同的目标,可以follow the guides provided by the gulp team

你最终会得到以下内容:

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

gulp.task('default', function () {
  var b = browserify({
    entries: './resources/test.js',
    debug: true,
    transform: [babelify.configure({
      presets: ['es2015']
    })]
  });

  return b.bundle()
    .pipe(source('./resources/test.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
      // Add other gulp transformations (eg. uglify) to the pipeline here.
      .on('error', util.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./public/js/'));
});