简体   繁体   English

用 Gulp 任务替换 CSS url

[英]Replace CSS url with Gulp task

I try to replace the path of a CSS file in index.html using Gulp.我尝试使用 Gulp 替换 index.html 中 CSS 文件的路径。 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索引.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在我的分发包中,主题被复制到src\\projects\\project\\app\\style\\themes 之类的东西下

dist/index.html分布/索引.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:这是使用 gulp-find 在 index.html 中查找 url 的尝试:

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?但是是否可以将此值与 gulp-replace 一起使用来更改 HTML 文件中的值?

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:但是 index.html 中的值是:

dist/[object Object]

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM