Lofka
Lofka

Reputation: 178

Grunt inject CSS file into <style> tag

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

Example :

Style.css

.foo { background:red; }

index-before.html ( Before Grunt task )

<html>
<head>

  <style type="text/css">

//output Style.css here

  </style>

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

index-after.html ( After Grunt task )

<html>
<head>

  <style type="text/css">

.foo { background:red; }

  </style>

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

Solution with grunt-replace (Thank 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>

Upvotes: 3

Views: 1736

Answers (1)

Andy
Andy

Reputation: 63514

Use replace.

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

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

Load your css file into a variable within your 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.

Upvotes: 3

Related Questions