2017-02-15 22 views
1

Я пытаюсь использовать Gulp + Browserify + Tsify, чтобы переместить 4 файла и их библиотеки в 4 файла js, которые в настоящее время принимают 4 или 5 секунд.Как использовать Browserify + Watchify + Tsify + Gulp в нескольких файлах ввода и быстро получить несколько выходных файлов

В моем текущем скрипте сборки отслеживание запускает обновление изменения любого ts-файла для всех 4 моих сборных трубок, каждый из которых traspiles каждый ts-файл в моем проекте, даже если он не используется в этом канале.

В настоящее время я ищу лучший и быстрый способ добиться этого.

import * as browserify from "browserify" 
import * as gulp from "gulp" 
import * as rename from "gulp-rename" 
import * as sass from "gulp-sass" 
import * as uglify from "gulp-uglify" 
import * as gutil from "gulp-util" 
import * as fs from "fs" 
import * as tsify from "tsify" 
import * as buffer from "vinyl-buffer" 
import * as source from "vinyl-source-stream" 
import * as watchify from "watchify" 
import {assign} from "lodash" 

const sassOptions: sass.Options = { 
    outputStyle: 'expanded' 
} 

function combinejs(update: boolean, minify: boolean) { 
    ['backScript.ts', 'mainFrame.ts', 'commentFrame.ts','script-inject.ts'].forEach(f => { 
     let b = browserify(assign({},watchify.args,{basedir:'src/', entries: f})), 
      bundle =() => { 
       let pipe = b.bundle().on('error',gutil.log) 
        .pipe(source(f)).pipe(rename({extname:'.js'})) 
       if (minify) { 
        pipe = pipe.pipe(buffer()).pipe(uglify()) 
       } 
       pipe.pipe(gulp.dest('build/files/src')) 
      } 
     b.plugin(tsify) 
     if (update){ 
      b.plugin(watchify,{}) 
      b.on('update',()=>{ 
       console.log({update:f}) 
       bundle() 
      }) 
     } 
     b.on('log', console.log) 
     console.log(f) 
     bundle() 
    }) 
} 

gulp.add('js',() => combinejs(false, true)) 

gulp.add('css',() => { 
    gulp.src('src/*.scss') 
     .pipe(sass(sassOptions)) 
     .pipe(gulp.dest('build/files/src')) 
}) 
gulp.add('copyFiles',() => { 
    gulp.src(['manifest.json', 'popup.html', 'images/*'], { base: '.' }) 
     .pipe(gulp.dest('build/files')) 
}) 

gulp.add("default", ['copyFiles','js', 'css']) 
gulp.add('build',['copyFiles','css'],()=>{ 
    combinejs(false,false) 
}) 

gulp.add("watch", ['copyFiles', 'css'],() => { 
    combinejs(true, false) 
    gulp.watch('src/*.scss', ['css']) 
}) 

ответ

0

Убедитесь, что вы за исключением библиотек (как jquery, lodash и т.д.)

Вы могли бы извлечь выгоду из factor-bundle (специально gulp-watchify-factor-bundle), чтобы разделить ваши записи вверх, но держать их общий код в отдельную библиотеку , Если у них много общего кода, он будет скомпилирован и дублирован в выводе каждой записи. tsify + gulp-watchify-factor-bundle, как представляется, не документированы, поэтому я догадываюсь о том, что вам может понадобиться:

const gulp = require("gulp"); 
const reduce = require("gulp-watchify-factor-bundle"); 
const buffer = require("vinyl-buffer"); 
const filelog = require("gulp-filelog"); 
const tsify = require("tsify"); 
const gutil = require("gulp-util"); 

const devenv = true; // bring your own env config 


function configuredUglify() { 
    return uglify(); // bring your own uglify 
} 

gulp.task("clean",() => { 
    return del("./bin/js"); 
}); 

// full builds 
gulp.task("build", ["clean"],() => { 
    const basedir = __dirname; 

    // browserify options here() 
    const b = reduce.create({ 
     basedir: basedir, 
     debug: devenv, 
     // the following may not apply to you 
     builtins: [], 
     insertGlobals: false, 
     detectGlobals: false, 
     browserField: false, 
     commondir: false 
    }); 

    // any large external libraries should be excluded (and loaded via <script src="..."> tags especially for development) 
    b.exclude("jquery"); 
    b.exclude("moment"); 

    b.plugin(tsify); 

    // NOTE: unlike browserify entries, reduce.src allows globs (like gulp.src) but will consider them a single bundle 
    // this is especially handy for unit tests! 
    return reduce.src(["backScript.ts", "mainFrame.ts", "commentFrame.ts", "script-inject.ts"], { cwd: basedir }) 
     // "outputs:" is required otherwise the .ts extension is kept (unlike jsify with vanilla browserify) 
     // full: 
     .pipe(reduce.bundle(b, { common: "sharedLib.js", outputs: ["backScripts.js", "mainFrame.js", "commentFrame.js", "script-inject.js"] })) 
     // incrementals: 
     // .pipe(reduce.watch(b, { common: "sharedLib.js", outputs: ["backScripts.js", "mainFrame.js", "commentFrame.js", "script-inject.js"] })) 

     // incrementals: 
     // .on("bundle", (vinylStream) => { /* vinylStream followed by lines below */ }) 

     .pipe(buffer()) 
     .pipe(devenv ? sourcemaps.init({ loadMaps: true, largeFile: true }) : gutil.noop()) // largeFile may be applicable 
     .pipe(!devenv ? configuredUglify() : gutil.noop()) 
     .on("error", gutil.log) 
     .pipe(devenv ? sourcemaps.write("./") : gutil.noop()) 
     .pipe(filelog("browserify")) 
     .pipe(reduce.dest("./bin/js/")); 
}); 

 Смежные вопросы

  • Нет связанных вопросов^_^