如何设置gulp将多个文件打包成一个文件?

12
这似乎是一个非常简单的问题,但我花了过去的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个回答

11

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

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/'));
});

3
正确的答案是:使用gulp拼接JS文件没有合法的需求。因此,你永远不应该这样做。
相反,应该研究适当的JS捆绑器,它们将按照某些已建立的格式(如commonsjs、amd、umd等)正确地连接您的文件并组织它们。
以下是更合适的工具列表:
- Webpack - Rollup - Parcel 请注意,我的回答是在2020年末左右,因此如果您在未来某个时候阅读本文,请记住JavaScript社区发展迅速,可能会出现新的更好的工具。

2
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();
});

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
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接