修改gulp文件以运行自定义的browserify命令

时间:2016-11-13 14:35:15

标签: node.js gulp browserify gulp-watch

我想在修改js文件(function.js)时使用gulp运行自定义browserify命令。

我要运行的browserify命令是;

$ browserify function.js --standalone function > bundle.js

我使用这个gulpfile.js作为示例。

https://github.com/gulpjs/gulp/blob/master/docs/recipes/fast-browserify-builds-with-watchify.md

如何修改此gulpfile以运行自定义的browserify命令?

'use strict';

var watchify = require('watchify');
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');

// add custom browserify options here
var customOpts = {
  entries: ['./src/index.js'],
  debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts)); 

// add transformations here
// i.e. b.transform(coffeeify);

gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
  return b.bundle()
    // log errors if they happen
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    // optional, remove if you don't need to buffer file contents
    .pipe(buffer())
    // optional, remove if you dont want sourcemaps
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
       // Add transformation tasks to the pipeline here.
    .pipe(sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./dist'));
}

我在webstorm上使用node.js v6.9。

1 个答案:

答案 0 :(得分:1)

您要运行的命令是;

$ browserify function.js --standalone function > bundle.js

基于此,修改后的代码是;

// add custom browserify options here
var customOpts = {
  entries: ['./function.js'],
  standalone: 'function',
};

只需在customOpts中为--standalone参数添加一个属性即可。其余代码保持不变。