2015-07-20 98 views
8

我不能正確加載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

你'你的入口點後。新增()'ING將會使填充工具負荷的方式。而不是'browserify(entryPoint',也許試試'browserify([require.resolve(「babel/polyfill」),entryPoint]' – loganfsmyth

+0

這是工作,我必須更加專心地學習文檔 非常感謝 –

回答

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

將創建一個包有兩個入口點,與entryPoint首先運行。這意味着在您的應用程序已加載之後,polyfill將加載。無論是做

require('babel/polyfill'); 

entryPoint文件中,或者把他們按正確的順序

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

Is there對於這個與webpack類似的修復?我試圖將一個項目轉換爲webpack,但在測試中得到相同的錯誤。 –

+0

正確,在webpack中你想改變'entry:'。/ app.js''或無論你有什麼需要輸入:['babel-polyfill','./app.js']' – loganfsmyth