如何将 href link 更改为 gulp

How to change a href link with gulp

我正在使用 gulp 创建一个需要更改 href 参数的任务。 例如:

在我的 html 文件中有一个 link:

<a href="myfolder">Click here</a>

所以,"myfolder"是可变的,指的是index.html所在文件夹的名称。 当我将文件推送到服务器上时,页面不显示为不针对 index.html 文件,而只是文件夹的名称。

我通过以下方式使用 gulp-replace 来完成任务:

var gulp = require('gulp');
var replace = require('gulp-replace');
 
gulp.task('templates', function(){
  gulp.src(['index.html'])
    .pipe(replace('<a href="*/" >', '<a href="*/index.html >"'))
    .pipe(gulp.dest('build/'));
});

由于文件夹名称 (myfolder) 是可变的,因为每次我处理项目时我都必须创建一个新文件夹,最后 index.html 文件不能只包含一个特定的名称。

所以,这个方法不行。

我们将不胜感激。

亲切的问候,

费尔南多

您需要在 replace 调用中定义一个正则表达式并匹配 href:

中的部分
replace(/<a href="(.*)"/g, '<a href="/index.html"')