gulp - 用 gulp 使用Sharp的正确方法是什么?
问题描述
我正在尝试将一堆 svg 转换为 png。但是由于 gulp-svg2png 和 gulp-sharp 的悲惨状态,我正在评估其他选项;锐利看起来很有希望。
版本:
$ gulp --version
CLI version: 2.2.0
Local version: 4.0.2
$ node -
Welcome to Node.js v13.6.0.
Type ".help" for more information.
> require('./package.json').dependencies.sharp
'^0.24.0'
不幸的是以下
gulp.task('svg-convert', function() {
var sharp = require('sharp')
gulp.src(config.svg2png)
.pipe(sharp().png())
.pipe(gulp.dest('./dist/images'))
});
发送此错误:
TypeError [ERR_INVALID_ARG_TYPE] [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer. Received an instance of File
at validChunk (_stream_writable.js:285:10)
at Sharp.Writable.write (_stream_writable.js:324:23)
...
(stacktrace continues)
有人解决了这个问题吗?
还是有更好的方法来处理这种特殊需求?
在@AlllainLG answer之后编辑。
这是我的两个镜头。不幸的是,两者都失败了。
gulp.task('svg2png', function() {
var sharp = require('sharp');
return gulp.src(c.svg2png)
.pipe(plug.each(function(content, file, callback) {
var newContent = sharp(content).png(); // here content is a buffer containing the image, newContent should be too?
// var newContent = sharp(content).png().toBuffer(); // this sends a Promise and fails
return callback(null, newContent);
}), 'buffer')
.pipe(plug.rename(function(path) {
return path.extname = ".png";
}))
.pipe(plug.imagemin())
.pipe(gulp.dest('./dist/images'));
});
这将没有任何东西传递到目的地:没有任何东西在./dist/images
.
第二次尝试使用 gulp-tap。
gulp.task('svg2png2', function() {
var sharp = require('sharp');
return gulp.src(c.svg2png)
.pipe(plug.tap(function(file) {
return file.contents = sharp(file.contents).png();
}))
.pipe(plug.rename(function(path) {
return path.extname = ".png";
}))
// .pipe(plug.imagemin()) // sends "Streaming not supported"
.pipe(gulp.dest('./dist/images'));
});
这会在目标中生成空文件(具有正确的名称)。
解决方案
以下工作,与 gulp-svg2png (平均 10 个复杂 svgs 约 540 毫秒)相比,具有约 100 毫秒(平均 10 个复杂 svgs 约 430 毫秒)的时间改进。
它使用through2。
除非有人有更好的答案,否则我会在大约一个月内接受这个答案。
gulp.task('svg2png', function() {
var sharp, through2;
sharp = require('sharp');
through2 = require('through2');
return gulp.src(c.svg2png)
.pipe(through2.obj(function(file, _, cb) {
return sharp(file.contents).png().toBuffer().then(function(buffer) {
file.contents = buffer;
return cb(null, file);
}).catch(function(err) {
console.error(err);
return cb(null, file);
});
}))
.pipe(plug.rename(function(path) {
return path.extname = ".png";
}))
.pipe(plug.imagemin())
.pipe(gulp.dest('./dist/images'));
});
推荐阅读
- python - Python Json 将值更改或重组为新键
- laravel - response()->file() 找不到位于 storage/app 的文件
- windows - 如何使用 docker 文件在 docker 容器中安装 powershell 模块
- android - 使用客户端证书反应本机请求
- html - 用 Dart 解析 Html 页面
- asp.net-core - 如何处理多个授权服务器以防止令牌颁发失败
- esp32 - 无法编译 ESP-IDF 示例项目
- javascript - 如何使用 JSON 数据将数据库中的选定文本设置为填充的级联下拉列表
- angular - 以角度将多个值从服务返回到组件
- node.js - 如何为自定义类验证器验证装饰器强制执行某些执行顺序