Amitabha Ghosh Amitabha Ghosh - 22 days ago 15
Javascript Question

Background image path not working in css file using gulp js

I am working on a project where I am concatenating all files, minifying and renaming by gulp.

When I write an image path as a background image in my main css file it is not working in the minified file. Actually I am unable to set the image path as it is getting compiled in my minified file which is in another directory.

My File route flow

assets -->
--css
--main.css
--img

dist -->
--css
--all-styles-min.css

gulpfile.js


I have put an image file inside the assets/img folder and am calling that file inside my main.css

My
gulp.js


return gulp.src([
'assets/css/animate.min.css',
'assets/css/bootstrap.css',
'assets/css/vendor/bootstrap-select.min.css',
'assets/css/vendor/bootstrap-datepicker3.min.css',
'assets/css/vendor/jquery.timepicker.css',
'assets/css/default.css',
'assets/css/main.css',
'assets/css/responsive.css',
])
.pipe(concat('all_styles.css'))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(rename('all_styles.min.css'))
.pipe(gulp.dest('dist/css'))
});


and in my
main.css


.black-bg{
background:url('../img/black-multiply-bg.png') 0 0 repeat;
}


I am seeing this console error for image file not found

http://localhost/projects/P-09-sakha/html/dist/css/assets/img/black-multiply-bg.png 404 (Not Found)


The source is showing the dist folder. I have also checked with gulp-css-url-adjuster but still am unable to make it work.

Answer

I have solved the issue of css-url-adjuster today while working for another project.

What I found the format of the coding was not correct for me before. So I am sharing in hope someone may find helpful from this.

For this I have used 4 Gulp plugins. 1. gulp-clean-css 2. gulp-cssmin 3. gulp-rename 4. gulp-css-url-adjuster

and the code is:

gulp.task('css', function(){
return gulp.src([
 '../html/assets/css/main.css',
  ])

/**
 *
 * Note
 * To Use minify and fixing the image path, you have
 * to use both gulp-clean-css & gulp-cssmin & gulp-css-url-adjuster
 * and the format must follow the below code
 * else you will get error
 */

.pipe(concat('apps.css'))
.pipe(gulp.dest('../html/assets/css'))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(urlAdjuster({
       prepend: '../img/',
      }))
.pipe(cssmin())
.pipe(rename({suffix:'.min'})) 
.pipe(gulp.dest('../html/assets/css'))
});