如何设置gulp将多个文件捆绑成一个文件?

z9zf31ra  于 2022-12-08  发布在  Gulp
关注(0)|答案(4)|浏览(188)

这似乎是一个非常简单的问题,但花了最后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文件中包含什么?
我至少需要在我的吞咽文件中写入什么?
这应该是尽可能快,所以我认为我应该使用browserify和watchify。我想了解最少的步骤,所以使用包管理器如jspm是矫枉过正的一点。
谢谢

ogsagwnx

ogsagwnx1#

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

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

46scxncf2#

正确的答案是:使用gulp连接JS文件是不合法的。2因此你永远不应该这样做。
相反,你应该寻找合适的JS捆绑器,它可以正确地将你的文件连接起来,按照一些既定的格式组织它们,比如commonsjs,amd,umd等等。
以下是更合适的工具列表:

请注意,我的答案是2020年年底左右,所以如果你在一个有点遥远的未来阅读这篇文章,请记住javascript社区发展很快,所以新的更好的工具可能会出现。

epggiuax

epggiuax3#

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

ix0qys7i4#

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

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

相关问题