gulp.dest输出目录问题
发布于 8 年前 作者 asins 11322 次浏览 来自 问答

想对指定目录中所有JS文件合并输成一个JS文件,

/work/gulpfile.js 文件内容如下:

"use strict";
const path = require('path');
const argv = require('yargs').argv;
const gulp = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const filter = require('gulp-filter');
const gutil = require('gulp-util');


gulp.task('js', (cb) => {
	const f = filter(['*', '!gulpfile.js', '!v5_build.js', '!v5_dest.js']);

	gulp.src(path.join(argv.d, './*.js'), {base: argv.d})
		.pipe(f)
		.pipe(concat('v5_build.js'))
		.pipe(uglify().on('error', gutil.log))
		.pipe(gulp.dest('./'))
		.on('end', cb);
});

/work/目录中执行 gulp js -d ./src/js/project1/

[20:32:20] Using gulpfile /work/gulpfile.js
[20:32:20] Starting 'js'...
[20:32:20] Finished 'js' after 43 ms

但在/work/src/js/project1/目录中没有输出对应的v5_build.js文件,不知问题出在哪里?

4 回复

base: argv.d 去了

第1种方法

将 cb 去了,直接 return stream see https://github.com/gulpjs/gulp/blob/master/docs%2FAPI.md#async-task-support

第2种

看下 stream 文档,Readable end是没有可读数据时,改成 Writable finish see https://nodejs.org/dist/latest-v4.x/docs/api/stream.html#stream_event_finish

end 应该没问题 https://nodejs.org/dist/latest-v4.x/docs/api/stream.html#stream_event_end

Note that the ‘end’ event will not fire unless the data is completely consumed.

上面的方法试过了不行,测试发现导致不成功是因为.pipe(f)这一行,看执行时候也说明未找到文件进入uglify步骤, 我自己未找到为啥filter后拿不到需要使用的文件,最后不使用gulp-filter模块改使用每次合并之前删除掉合并后的文件解决问题,需要并不是理想中的做法。

最终代码:

gulp.task('js', (cb) => {
	del.sync([ // 先删除合并的文件
		path.join(argv.d, './v5_build.js'),
		path.join(argv.d, './v5_dest.js'),
	])

	gulp.src(path.join(argv.d, './*.js'))
		.pipe(concat('v5_build.js'))
		.pipe(gulp.dest(argv.d)) // v5_build.js

		.pipe(rename({basename: 'v5_dist'}))
		.pipe(uglify().on('error', gutil.log))
		.pipe(gulp.dest(argv.d)) // v5_dist.js
		.on('end', cb);
});
回到顶部