【问题标题】:Grunt inject CSS file into <style> tagGrunt 将 CSS 文件注入 <style> 标签
【发布时间】:2015-05-11 15:52:59
【问题描述】:

我正在寻找使用 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>

【问题讨论】:

  • 我认为不仅重复,而且太宽泛,可能要求图书馆。
  • 您知道是否有一种方法可以在不复制构建文件夹中的 HTML 文件的情况下使其工作?理想情况下,只需通过唯一 ID 替换样式标签内的内容。这样你就只有一个文件了。

标签: javascript gruntjs


【解决方案1】:

使用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 文档,您应该为您的系统找出它。

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 2018-08-09
    • 2020-10-09
    • 1970-01-01
    • 2016-03-05
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    相关资源
    最近更新 更多