190.gulp给文件重命名

在cmd窗口进入项目所在的文件夹,执行:npm install gulp-rename --save-dev

--save-dev就是将此安装包,安装在该项目中,并且将安装包记录到项目中的package.json中。
由之前对css文件进行压缩处理的情况来看,可以很好地进行文件的压缩,但是压缩过后的文件,保存到另外一个文件夹中还是原来未压缩的时候的文件名,这样的话,在进行引用的时候,他就不知道到底是没有压缩的文件,还是经过压缩的文件了,所以我们可以将压缩过的文件进行重命名,示例代码如下:
//在js中导入nodo中的包的时候,需要使用到一个函数require()
//只需要将所需要导入的包传递给require()函数就可以了
var gulp =require('gulp');
var cssnano = require('gulp-cssnano');
var rename = require('gulp-rename');


gulp.task('css', function() {
    gulp.src('./css/*.css')
    .pipe(cssnano())
    //这个命令规则就是在经过压缩过后的文件候命加上一个后缀为min
    .pipe(rename({
        'suffix':'.min'
    }))
    .pipe(gulp.dest('./dist/css/'))
});
其中,gulp-rename的相关介绍可以详细的查看:https://www.npmjs.com/package/gulp-rename
在这里摘录了rename的相关使用:
var rename = require("gulp-rename");
 
// rename to a fixed value
gulp.src("./src/main/text/hello.txt")
    //rename the filename
  .pipe(rename("main/text/ciao/goodbye.md"))
  //the destination
  .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/goodbye.md
 
// rename via mutating function
gulp.src("./src/**/hello.txt")
  .pipe(rename(function (path) {
    // Updates the object in-place
    path.dirname += "/ciao";
    path.basename += "-goodbye";
    path.extname = ".md";
  }))
  .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/hello-goodbye.md
 
// rename via a map function
gulp.src("./src/**/hello.txt")
  .pipe(rename(function (path) {
    // Returns a completely new object, make sure you return all keys needed!
    return {
      dirname: path.dirname + "/ciao",
      basename: path.basename + "-goodbye",
      extname: ".md"
    };
  }))
  .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/hello-goodbye.md
 
// rename via a fixed object
gulp.src("./src/main/text/hello.txt", { base: process.cwd() })
  .pipe(rename({
    dirname: "main/text/ciao",
    basename: "aloha",
    prefix: "bonjour-",
    suffix: "-hola",
    extname: ".md"
  }))
  .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md
始于才华,忠于颜值;每件事情在成功之前,看起来都是天方夜谭。一无所有,就是无所不能。
原文地址:https://www.cnblogs.com/guyan-2020/p/12387337.html