I need to insert the content of a stylesheet into the <head>
of an HTML page. How can I do it in 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 can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.
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>\n' + style + '\n</style>';
}))
.pipe(gulp.dest(...));
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>\n' + style + '\n</style>';
}))
.pipe(gulp.dest(...));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With