How to use a stream as input for Browserify?

In Gulp, I'm trying to compile TypeScript, concatenate it, then run it through Browserify to handle the require s (then uglify after if in production mode).

This sample code is the closest I've found to what I'm trying to do, however it uses an intermediary file. I'd much rather keep things to the stream to avoid the overhead of the intermediary file if at all possible.

Since Browserify outputs a stream, it seems like it should know how to accept one as well.

The relevant code:

var gulp = require('gulp');
var browserify = requ
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var transform = require('vinyl-transform');
var typeScript = require('gulp-typescript');

gulp.task('scripts', function () {
    return gulp.src([mySrcDir,'typings/**/*.d.ts'])
        .pipe(sourcemaps.init())
        .pipe(typeScript(typeScriptProject))
        .pipe(concat('main.js'))
        .pipe(transform(function (filename) {
            return browserify(filename).bundle();
        }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(ns.outDir))
        // Reload, notify...
        ;

The result:

Error: Cannot find module 'C:pathtoprojectrootsrcmain.js' in 'C:pathtoprojectroot'

When I omit concatenation, the result is the same, except with foobar.js instead of main.js where foobar.ts is one of the input files.

A second attempt

gulp.task('scripts', function () {
    var stream = gulp.src([mySrcDir,'typings/**/*.d.ts'])
        .pipe(sourcemaps.init())
        .pipe(typeScript(typeScriptProject))
        .pipe(concat('main.js'));
    var bundleStream = ns.browserify(stream).bundle().on('error', errorHandler);
    // and then...

A new error

C:pathtoprojectroot_stream_0.js:1
[object Object]
        ^
ParseError: Unexpected token

You can't pass a vinyl stream to browserify. It only accepts text or buffer streams. The only solution is to transform the input vinyl stream to a text stream that browserify can grasp:

var gutil = require('gulp-util')
var through = require('through2')
var intoStream = require('into-stream')

// ...
.pipe(through.obj(function(file, encoding, next) {
  bundle = browserify(intoStream(file.contents))
  this.push(new gutil.File({
    path: 'index.js',
    contents: bundle.bundle()
  }))
  next()
}))

take a look at gulp-browserify, it a gulp plugin for browserify.

Example:

gulp.src([mySrcDir,'typings/**/*.d.ts'])
    .pipe(sourcemaps.init())
    .pipe(typeScript(typeScriptProject))
    .pipe(concat('main.js'))
    .pipe(browserify(options)
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(ns.outDir))
    // Reload, notify...
    ;

for options you may refer to the link posted above

链接地址: http://www.djcxy.com/p/24096.html

上一篇: 使用gulp编译LESS

下一篇: 如何使用流作为Browserify的输入?