Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use grunt-uncss with an AngularJS application?

My AngularJS application is composed by two urls:

  • http://myapp/#/foo
  • http://myapp/#/bar

This is the simplified index.html file:

<html>

  <head>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>

  <body>
    <div ui-view></div>
  </body>

  <script type="text/javascript" src="script.js"></script>

</html>

In addition to containing the application logic, the script.js file also contains the html templates that are loaded via $templateCache service.

With the http://myapp/#/foo url, the foo html template is inserted in the <div ui-view></div> element. In the same way, with the http://myapp/#/bar url, the bar html template is inserted in <div ui-view></div>.

What I want to do is to use the grunt-uncss task to reduce the style.css size.

My first attempt was:

uncss: {
  dist: {  
    files: {
      'style.css': [ 'index.html' ]
    }
}

The style.css file was reduced, but it did not included the styles required by the foo and bar pages.

My second attempt was using the deprecated urls parameter to be loaded with PhantomJS:

uncss: {
  options: {
    urls; [ 'http://myapp/#/foo', 'http://myapp/#/bar' ]
  },
  dist: {  
    files: {
      'style.css': [ 'index.html' ]
    }
}

Again, the style.css file was reduced, but it did not included the styles required by the foo and bar pages.

Someone knows how to solve this problem?

Does grunt-uncss only work with static content?

Thanks in advance,

Bernardo Pacheco

like image 967
Bernardo Pacheco Avatar asked Oct 29 '14 19:10

Bernardo Pacheco


1 Answers

Specify all your html files, including views:

uncss: {
    dist: {
        options: {
            ignore: ['.ng-move', '.ng-enter', '.ng-leave', '.created_by_jQuery']
        },
        files: {
            'style.css': [ 'index.html', 'views/foo.html', 'views/bar.html' ]
        }
    }
}

You can specify more than one file of html, so you should include all your view files (in this case foo.html and bar.html). Also, use ignore option to add classes that are loaded at runtime (do not already exist in html files), i.e. created by jQuery, or ngAnimate if you are using one.

There are more options, for example you can customize which media queries should be left after uncssing, please refer to the documentation provided by authors - https://github.com/addyosmani/grunt-uncss.

like image 58
minijus Avatar answered Nov 10 '22 17:11

minijus