Babel填充器和Gulp

11

在使用gulp时,我无法正确加载babel/polyfill库。在我的情况下,Array.from方法未定义。 然而,如果我尝试使用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
你现在使用的 .add() 方法会使 polyfill 在入口点之后加载。建议尝试 browserify([require.resolve("babel/polyfill"), entryPoint] 替代 browserify(entryPoint) - loganfsmyth
这个程序可以工作。我需要更加专注地学习文档。非常感谢。 - Kirill A. Khalitov
1个回答

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

将创建一个带有两个入口点的包,其中entryPoint首先运行。这意味着多填充程序将在您的应用程序加载后加载。可以执行以下操作:

require('babel/polyfill');

在您的entryPoint文件中添加它们,或按正确顺序排列。
browserify(["babel/polyfill", entryPoint], { debug: watch })

有没有类似的解决方案适用于webpack?我正在尝试将一个项目转换为webpack,但在测试中遇到了相同的错误。 - Mary Camacho
在webpack中,你需要将entry: './app.js'或者其他的内容更改为entry: ['babel-polyfill', './app.js'] - loganfsmyth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接