Babel polyfill和gulp

时间:2015-07-20 15:05:13

标签: javascript gulp browserify ecmascript-6 babeljs

我无法正确加载babel/polyfill gulp。在我的情况下,Array.from方法未定义。 但是,如果尝试使用gulp browser-polyfill.js加载.add(require.resolve("babel/polyfill")),我会收到错误"only one instance of babel/polyfill is allowed"。 源代码是正确的,因为我用babel browser-polyfill.js测试了它。

源代码:

//Lib.js
export default class Lib
{
  constructor()
  {
    var src = [1, 2, 3];
    this.dst = Array.from(src);
  }
  foo()
  {
    return this.dst;
  }
}

//main.js
import Lib from "./Lib";

var l = new Lib();
console.log(l.foo()); //Uncaught TypeError: Array.from is not a function

Gulpfile:

var gulp       = require('gulp');
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 babelify   = require('babelify');
var uglify     = require('gulp-uglify');

var entryPoint = "./js/main.js";


function compile(watch)
{
  var bundler;

  function debug()
  {
    bundler.bundle()
    .on('error', function(err) { console.error(err); this.emit('end'); })
    .pipe(source('main.debug.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./bin'));
  }

  function release()
  {
    bundler.bundle()
    .on('error', function(err) { console.error(err); this.emit('end'); })
    .pipe(source('main.release.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest('./bin'));
  }

  if(watch)
  {
    bundler = watchify(browserify(entryPoint, { debug: watch })
                        .add(require.resolve("babel/polyfill"))
                        .transform(babelify));

    bundler.on('update', function()
    {
      console.log('Sources has changed. Rebuilding...');
      debug();
    });

    debug();
  }
  else
  {
    bundler = browserify(entryPoint, { debug: watch })
              .add(require.resolve("babel/polyfill"))
              .transform(babelify);
    release();
  }
}


gulp.task('release', function() { return compile(false); });
gulp.task('debug',   function() { return compile(true); });

gulp.task('default', ['debug']);

1 个答案:

答案 0 :(得分:7)

browserify(entryPoint, { debug: watch })
          .add("babel/polyfill")

将创建一个包含两个入口点的捆绑包,首先运行entryPoint。这意味着polyfill将在应用程序加载后加载。 <或者

require('babel/polyfill');

entryPoint文件中,或按正确的顺序排列

browserify(["babel/polyfill", entryPoint], { debug: watch })