每当更改 js 文件时自动执行此 browserify 命令

Automate this browserify command whenever js file is changed

每当我更改 function.js 时,我必须手动 运行 下面的命令将 function.js 浏览器化为 bundle.js

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

如何使此步骤自动化,以便每当 function.js 被修改时命令在后台自动 运行?

我在 Windows 10 上使用 node.js v6.9 和 Webstorm 2016.2。

您要 运行 的 browserify 命令是;

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

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

这是您需要的完整代码。选择 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: ['./function.js'],
  standalone: 'function',
};
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'));
}

watchify 非常简单,只需安装 npm i -D watchify

然后使用命令 "watch" : "npx watchify <source>.js -o <output>.js"

更新您的 'package.json' 文件

您已经准备好使用 运行 您的 npm 命令 npm run watch