Browserify不会替换类令牌

时间:2016-01-11 17:01:48

标签: gulp ecmascript-6 browserify babeljs

我正在使用以下gulpfile将我的javascript代码从ES6编译为ES5。

var gulp = require('gulp');
var gutil = require('gulp-util');
var cssnano = require('gulp-cssnano');
var autoprefixer = require('gulp-autoprefixer');
var notify = require("gulp-notify");
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babel = require('gulp-babel');
var babelify = require('babelify');
var uglify = require('gulp-uglify');

//...

gulp.task('js', function () {
    return buildScript('index.js', false);
});


function buildScript(file, watch) {

    var props = {
        entries: [folder_source + '/javascript/' + file],
        debug : true,
        transform:  [babelify]
    };

    // watchify() if watch requested, otherwise run browserify() once
    var bundler = watch ? watchify(browserify(props)) : browserify(props);

    function rebundle() {
        var stream = bundler.bundle();
        return stream
            .on('error', handleErrors)
            .pipe(source(file))
            .pipe(gulp.dest(folder_dest + '/javascript/build/'));
    }

    // listen for an update and run rebundle
    bundler.on('update', function() {
        rebundle();
        gutil.log('Rebundle...');
    });

    // run it once the first time buildScript is called
    return rebundle();
}


function handleErrors() {
    var args = Array.prototype.slice.call(arguments);
    notify.onError({
        title: 'Compile Error',
        message: '<%= error.message %>'
    }).apply(this, args);
    this.emit('end'); // Keep gulp from hanging on this task
}

一切正常,直到我开始真正使用ES6。

示例源(index.js):

class Car{

}

编译示例(app.js):

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
class Car {}

},{}]},{},[1])

正如您所看到的,编译文件中仍然存在ES6代码。 似乎babelify没有做它的jop。我已经尝试过来自网络上的其他几个gulp文件,但我总是得到相同的结果。

谢谢!

1 个答案:

答案 0 :(得分:0)

感谢loganfsmyth我能够通过在props数组中添加以下内容来解决问题:

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