[英]What regex can I use to match CSS and JavaScript links in an HTML document?
I'm using a simple gulp task for "minifying" my CSS and JS files. 我正在使用一个简单的gulp任务来“缩小”我的CSS和JS文件。 The task adds a
.min
suffix to the name of the minified files. 该任务将
.min
后缀添加到缩小文件的名称中。 I'd like to update the HTML to point to the new, compressed files eg: 我想更新HTML以指向新的压缩文件,例如:
Change this: 更改此:
<link ... href="...some_name.css ..." ...>
To this: 对此:
<link ... href="...some_name.min.css ..." ...>
I use gulp-string-replace plugin , but I can't figure out the right regex to target JS and CSS links. 我使用的是gulp-string-replace插件 ,但是我找不到适合JS和CSS链接的正则表达式。 I don't want to hardcode filenames and I obviously can't just match for the strings
.css
or .js
. 我不想对文件名进行硬编码,显然我不能只匹配字符串
.css
或.js
。
Sample tasks: 示例任务:
var replace = require('gulp-string-replace');
gulp.task('replace_1', function() {
gulp.src(["./config.js"]) // Any file globs are supported
.pipe(replace(new RegExp('@env@', 'g'), 'production'))
.pipe(gulp.dest('./build/config.js'))
});
gulp.task('replace_2', function() {
gulp.src(["./index.html"])
.pipe(replace(/version(={1})/g, '$1v0.2.2'))
.pipe(gulp.dest('./build/index.html'))
});
gulp.task('replace_3', function() {
gulp.src(["./config.js"])
.pipe(replace(/foo/g, function () {
return 'bar';
}))
.pipe(gulp.dest('./build/config.js'))
});
这将解决您的问题,但将包括所有CSS文件链接。
replace(/href=\"(\S*)\.css\"/gi, 'href="$1.min.css"')
The usual way to do this would be to incorporate something like the gulp-processhtml plugin in your workflow. 通常的方法是在工作流程中加入gulp-processhtml插件之类的东西。 It is designed to do exactly what you are doing.
它旨在完全按照您的工作来做。
<!-- build:css style.min.css -->
<link rel="stylesheet" href="css/style.css">
<!-- /build -->
becomes simply 变得简单
<link rel="stylesheet" href="style.min.css">
Here is a gulp 4.0 task I use when moving a development version of the html to a deployment directory: 这是将html的开发版本移动到部署目录时使用的gulp 4.0任务:
var stripComments = require("gulp-strip-comments");
var modifyHTMLlinks = require("gulp-processhtml");
var addVersionString = require("gulp-version-number");
var print = require('gulp-print').default;
function processHTML() {
return gulp.src(paths.html.src)
.pipe(print())
// modifyHTMLlinks: remove browserSync script link
// update css/js links to .min.css or .min.js
.pipe(modifyHTMLlinks())
.pipe(stripComments.html(stripOptions))
// add ?v=dateTime stamp to css and js links
.pipe(addVersionString(versionConfig))
.pipe(gulp.dest(paths.html.deploy));
}
This seems much more foolproof than messing with regex's but perhaps you have some reason to avoid such a plugin? 这似乎比使用正则表达式要简单得多,但也许您有某些理由要避免使用此类插件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.