本文介紹了如何在 Gulp 中將 CSS 文件的內容注入 HTML?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我需要將樣式表的內容插入到 HTML 頁面的 <head>
中.我如何在 Gulp 中做到這一點?
I need to insert the content of a stylesheet into the <head>
of an HTML page. How can I do it in Gulp?
之前(我所擁有的):
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
之后(我想要的):
<head>
<style>
p { color: pink; }
</style>
</head>
請注意,我不需要將 CSS 內聯到元素中,只需將 CSS 的內容放在 <head>
中即可.
Note that I do not need to inline CSS into the elements, but just put the contents of CSS in the <head>
.
推薦答案
你可以輕松使用 gulp-replace
,像這樣:
You could easily use gulp-replace
, like so:
var gulp = require('gulp'),
replace = require('gulp-replace'),
fs = require('fs');
// in your task
return gulp.src(...)
.pipe(replace(/<link href="style.css"[^>]*>/, function(s) {
var style = fs.readFileSync('style.css', 'utf8');
return '<style>
' + style + '
</style>';
}))
.pipe(gulp.dest(...));
您還可以輕松修改替換 RegEx 以處理不同的文件.
You can also easily modify the replacement RegEx to work with different files, too.
return gulp.src(...)
.pipe(replace(/<link href="([^.].css)"[^>]*>/g, function(s, filename) {
var style = fs.readFileSync(filename, 'utf8');
return '<style>
' + style + '
</style>';
}))
.pipe(gulp.dest(...));
這篇關于如何在 Gulp 中將 CSS 文件的內容注入 HTML?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!