How to inject content of CSS file into HTML in Gulp? [closed]

淺唱寂寞╮ 提交于 2019-12-03 03:36:01

问题


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>.


回答1:


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(...));



回答2:


You can inline the styles using import:

<style> @import "style.css"; </style>


来源:https://stackoverflow.com/questions/23820703/how-to-inject-content-of-css-file-into-html-in-gulp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!