Grunt将CSS文件注入标签

时间:2022-12-12 20:18:27

I am looking for a solution for injecting a CSS file into a style tag with Grunt.

我正在寻找一个使用Grunt将CSS文件注入样式标记的解决方案。

Example :

Style.css

.foo { background:red; }

index-before.html ( Before Grunt task )

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

<html>
<head>

  <style type="text/css">

//output Style.css here

  </style>

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

index-after.html ( After Grunt task )

index-after.html(在Grunt任务之后)

<html>
<head>

  <style type="text/css">

.foo { background:red; }

  </style>

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

Solution with grunt-replace (Thank Andy)

使用grunt替换解决方案(感谢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>

1 个解决方案

#1


Use replace.

In your HTML use a indicator that is recognised by replace:

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

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

Load your css file into a variable within your Gruntfile.js:

将css文件加载到Gruntfile.js中的变量中:

var css = grunt.file.read(cssfilepath [, options]);

Then add a replace task, something like:

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

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

Note, I've not tested this, but if you follow the replace documentation you should figure it out for your system.

请注意,我没有对此进行过测试,但是如果您按照替换文档进行测试,则应该为您的系统找到它。

#1


Use replace.

In your HTML use a indicator that is recognised by replace:

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

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

Load your css file into a variable within your Gruntfile.js:

将css文件加载到Gruntfile.js中的变量中:

var css = grunt.file.read(cssfilepath [, options]);

Then add a replace task, something like:

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

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

Note, I've not tested this, but if you follow the replace documentation you should figure it out for your system.

请注意,我没有对此进行过测试,但是如果您按照替换文档进行测试,则应该为您的系统找到它。