E
E
Evgeny Popov2017-07-10 19:31:41
css
Evgeny Popov, 2017-07-10 19:31:41

How to configure Gulp to write file paths correctly?

There is a small Gulp starter template where I compile the less files into a single css file. Gulp task example:

gulp.task('less', function () {  
    return gulp.src('app/less/**/*.less')
    	.pipe(less().on("error", notify.onError()))
        .pipe(less({
            paths: [ path.join(__dirname, 'less', 'includes') ]
        }))
       	.pipe(concat('main.min.css'))
        .pipe(cleanCSS())
        .pipe(gulp.dest('app/css'))
        .pipe(browserSync.reload({stream: true}));
});

It seems everything works, but I can not figure out the paths of the file locations. For example, my less is divided into blocks that are nested in folders. There the path is allowed to the background is written
background: url(../../img/angle_up.png) no-repeat 97% 50%;
But here's how to make sure that during assembly, the path is automatically correctly written, and not left as it is. Of course, I looked at ready-made starter templates from different developers, where there are different file nestings, but I just can’t figure out which plugin does this. Who can help?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav, 2017-07-10
@12evgen

In general, here you need to understand that all such tasks in Gulp are usually solved due to certain plugins for it. So, specifically for your task, the gulp-modify-css-urls plugin is suitable. First you need to install it:
Specify the --save-dev option if you want this dependency to be written into your package.json in the dev section. After that you can modify paths in css files with code like this (taken from the plugin's docs):

var gulp = require('gulp')
  , modifyCssUrls = require('gulp-modify-css-urls');
 
/* style.css
body {
  background-image: url('images/logo.png');
}
*/
gulp.task('modifyUrls', function () {
  return gulp.src('style.css')
    .pipe(modifyCssUrls({
      modify: function (url, filePath) {
        return 'app/' + url;
      },
      prepend: 'https://fancycdn.com/',
      append: '?cache-buster'
    }))
    .pipe(gulp.dest('./'));
});
/* style.css
body {
  background-image: url('https://fancycdn.com/app/images/logo.png?cache-buster');
}
*/

Everything seems to be clearly commented in the code, but if anything, ask for clarification. In general, there is an option to immediately write LESS files in such a way that you do not have to edit them later. But this, of course, is a matter of taste, and it’s not very convenient to develop code anyway, of course.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question