9

这似乎是一个非常简单的问题,但花了最后 3 个小时研究它,发现如果不使用 watchify,每次保存新文件都会很慢。

这是我的目录树:

gulpfile.js
package.json

www/
  default.htm
     <script src="toBundleJsHere/file123.js"></script>

  toBundletheseJs/
    componentX/
       file1.js
    componentY/
       file2.js
    componentZ/
      file3.js

  toPutBundledJsHere/
      file123.js

要求。在文件夹中每次创建或保存文件时,toBundleTheseJs/我希望将此文件重新捆绑到toBundleJsHere/

我需要在我的package.json文件中包含什么?

我需要写入我的 gulp 文件的最低要求是多少?

这应该尽可能快,所以认为我应该使用 browserify 和 watchify。我想了解最少的步骤,所以在这一点上使用像 jspm 这样的包管理器是多余的。

谢谢

4

4 回答 4

10

首先,您应该收听所需目录中的更改:

watch(['toBundletheseJs/**/*.js'], function () {
        gulp.run('bundle-js');
    });

然后该bundle-js任务应该捆绑您的文件。推荐的方法是gulp-concat

var concat = require('gulp-concat');
var gulp = require('gulp');

gulp.task('bundle-js', function() {
  return gulp.src('toBundletheseJs/**/*.js')
    .pipe(concat('file123.js'))
    .pipe(gulp.dest('./toPutBundledJsHere/'));
});
于 2016-03-05T19:17:02.667 回答
3

正确的答案是:没有必要使用 gulp 连接 JS 文件。因此,您永远不应该这样做。

相反,请查看合适的 JS 捆绑器,它们将根据某些既定格式(如 commonsjs、amd、umd 等)正确连接您的文件来组织它们。

以下是更合适的工具列表:

请注意,我的答案是在 2020 年底左右,所以如果您在遥远的将来阅读这篇文章,请记住 javascript 社区发展迅速,因此可能会出现新的更好的工具。

于 2020-12-29T13:59:30.020 回答
1
var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('js', function (done) {
    // array of all the js paths you want to bundle.
    var scriptSources = ['./node_modules/idb/lib/idb.js', 'js/**/*.js'];
    gulp.src(scriptSources)
        // name of the new file all your js files are to be bundled to.
        .pipe(concat('all.js'))
        // the destination where the new bundled file is going to be saved to.
        .pipe(gulp.dest('dist/js'));
    done();
});
于 2018-06-09T12:46:33.613 回答
1

使用此代码将多个文件捆绑为一个。

gulp.task('scripts', function() {
      return gulp.src(['./lib/file3.js', './lib/file1.js', './lib/file2.js']) //files separated by comma
        .pipe(concat('script.js'))   //resultant file name
        .pipe(gulp.dest('./dist/')); //Destination where file to be exported
    });
于 2019-06-28T09:48:10.263 回答