Rename the file based on the regular expression in Gulp

Let's say I have a LESS CSS directory structure like this:

less/ core/ _main.less header.less body.less footer.less contact/ _main.less form.less details.less 

I want to write a Gulp task that will look for _main.less files in each subdirectory of the less/ directory, transfer this to gulp -less and write the output to the css/ directory in this:

 css/ core.css contact.css 

Since _main.less includes other files in this directory, only _main.less files will need to be _main.less , but I want the output file to have the name of the directory in which it is located.

So far I have this:

 gulp.src('less/*/*/_main.less') .pipe(less()) .pipe(gulp.dest('css')); 

But this will create a directory structure like this:

 css/ core/ _main.css contact/ _main.css 

But that is not what I want. I thought of using a regular expression to match the directory name, return it to matches var, and rename the file accordingly. Something like that:

 gulp.src(/less\/[^\/]+\/([^\/]+)\/_main.less/) .pipe(less()) .pipe(rename(function(context) { context.src.matches[1] + '.css' })) .pipe(gulp.dest('css')); 

This code is just an example. I cannot figure out how to do this, or if it is possible.

Is it possible? If so, how?

+6
source share
1 answer

Do you look like you already have this, but you may not have seen the gulp-rename plugin ?

I don’t even think you need to use RegExp , something like this should work:

 var rename = require('gulp-rename'), path = require('path'); // node Path //... gulp.src('less/**/_main.less') .pipe(less()) .pipe(rename(function(filepath) { // replace file name to that of the parent directory filepath.basename = path.basename(filepath.dirname); // remove parent directory from relative path filepath.dirname = path.dirname(filepath.dirname); // leave extension as-is })) .pipe(gulp.dest('css')); 
+8
source

Source: https://habr.com/ru/post/974496/


All Articles