javascript 如何在 Gulp 中将 CSS 文件的内容注入 HTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23820703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to inject content of CSS file into HTML in Gulp?
提问by Evgenii
I need to insert the content of a stylesheet into the <head>
of an HTML page. How can I do it in Gulp?
我需要将样式表的内容插入到<head>
HTML 页面的 中。我怎样才能在 Gulp 中做到这一点?
Before (what I have):
之前(我拥有的):
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
After (what I want):
之后(我想要的):
<head>
<style>
p { color: pink; }
</style>
</head>
Note that I do not need to inline CSS into the elements, but just put the contents of CSS in the <head>
.
请注意,我不需要将 CSS 内联到元素中,而只需将 CSS 的内容放在<head>
.
回答by OverZealous
You could easily use gulp-replace
, like so:
您可以轻松使用gulp-replace
,如下所示:
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>\n' + style + '\n</style>';
}))
.pipe(gulp.dest(...));
You can also easily modify the replacement RegEx to work with different files, too.
您还可以轻松修改替换 RegEx 以处理不同的文件。
return gulp.src(...)
.pipe(replace(/<link href="([^\.]\.css)"[^>]*>/g, function(s, filename) {
var style = fs.readFileSync(filename, 'utf8');
return '<style>\n' + style + '\n</style>';
}))
.pipe(gulp.dest(...));
回答by Kim T
You can inline the styles using import:
您可以使用 import 内联样式:
<style> @import "style.css"; </style>