Search code examples
htmlcssgulpgulp-rename

Replace CSS url with Gulp task


I try to replace the path of a CSS file in index.html using Gulp. The problem is I have multiple projects with different theme name, and the path of the source file is different in the distribution package

index.html

<link href="app/style/themes/dark/theme.css" id="hmi-theme" rel="stylesheet" />

In my distribution package, the theme is copied under something like src\projects\project\app\style\themes

dist/index.html

<link href="[set the path here/]app/style/themes/dark/theme.css" id="hmi-theme" rel="stylesheet" />

Here is an attempt with gulp-find to find the url in index.html:

var gulp = require('gulp');
var find = require('gulp-find');
var replace = require('gulp-replace');

gulp.task('templates', function(){
    gulp.src(['index.html'])
        .pipe(find(/app\/style\/themes\/([^"]*)/g))
        .pipe(gulp.dest('file.txt'));

That works, I've got the value in the destination file. But is it possible to use this value with gulp-replace to change the value in the HTML file?

I've tried also something like:

.pipe(replace(/app\/style\/themes\/([^"]*)/g, "dist/" + find(/app\/style\/themes\/([^"]*)/g)))

But the value in index.html was:

dist/[object Object]

Solution

  • Ok, I've finally found a solution:

    return gulp.src(path.join(projectDir, 'index.html'))
      .pipe(replace(/app\/style\/themes\/([^"]*)/g, function(cssPath) {
          return "my-new-path/" + cssPath;
      } ))
      .pipe(gulp.dest(distDir));