Grunt 将 CSS 文件注入 <style> 标签

Grunt inject CSS file into <style> tag

我正在寻找使用 Grunt 将 CSS 文件注入 style 标签的解决方案。

示例:

Style.css

.foo { background:red; }

index-before.html(在 Grunt 任务之前)

<html>
<head>

  <style type="text/css">

//output Style.css here

  </style>

</head>
<body>
....
</body>
</html>

index-after.html(Grunt 任务后)

<html>
<head>

  <style type="text/css">

.foo { background:red; }

  </style>

</head>
<body>
....
</body>
</html>

用 grunt-replace 解决(感谢 Andy)

replace: {
    dist: {
        options: {
            patterns: [
                {
                    match: 'include_css_style_tag',
                    replacement: '<%= grunt.file.read("assets/css/styles.css") %>'
                }
            ]
        },
        files: [
            {expand: true, flatten: true, src: ['index.html'], dest: 'build/'}
        ]
    }
}

index.html

<style type="text/css">
@@include_css_style_tag
</style>

使用replace.

在您的 HTML 中使用被 replace 识别的指标:

<style type="text/css">
  @@mycss
</style>

Load your css file 到您的 Gruntfile.js:

中的一个变量
var css = grunt.file.read(cssfilepath [, options]);

然后添加替换任务,例如:

replace: {
  dist: {
    options: {
      patterns: [{
        match: 'mycss',
        replacement: css
      }]
    },
    files: [{
      expand: true,
      flatten: true,
      src: ['src/index.html'],
      dest: 'src/index.html'
    }]
  }
};

请注意,我没有对此进行测试,但如果您遵循 replace 文档,您应该为您的系统找到它。