Code Monkey home page Code Monkey logo

grunt-uncss's Introduction

UnCSS

npm version Build Status Coverage Status

UnCSS is a tool that removes unused CSS from your stylesheets. It works across multiple files and supports Javascript-injected CSS.

How

The process by which UnCSS removes the unused rules is as follows:

  1. The HTML files are loaded by jsdom and JavaScript is executed.
  2. All the stylesheets are parsed by PostCSS.
  3. document.querySelector filters out selectors that are not found in the HTML files.
  4. The remaining rules are converted back to CSS.

Please note:

  • UnCSS cannot be run on non-HTML pages, such as templates or PHP files. If you need to run UnCSS against your templates, you should probably generate example HTML pages from your templates, and run uncss on those generated files; or run a live local dev server, and point uncss at that.
  • UnCSS only runs the Javascript that is run on page load. It does not (and cannot) handle Javascript that runs on user interactions like button clicks. You must use the ignore option to preserve classes that are added by Javascript on user interaction.

Installation

npm install -g uncss

Usage

Online Server

Within Node.js

var uncss = require('uncss');

var files = ['my', 'array', 'of', 'HTML', 'files', 'or', 'http://urls.com'],
    options = {
        banner: false,
        csspath: '../public/css/',
        htmlroot: 'public',
        ignore: ['#added_at_runtime', /test\-[0-9]+/],
        ignoreSheets: [/fonts.googleapis/],
        inject: function (window) {
            window.document.querySelector('html').classList.add('no-csscalc', 'csscalc');
        },
        jsdom: {
            userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)',
        },
        media: ['(min-width: 700px) handheld and (orientation: landscape)'],
        raw: 'h1 { color: green }',
        report: false,
        strictSSL: true,
        stylesheets: ['lib/bootstrap/dist/css/bootstrap.css', 'src/public/css/main.css'],
        timeout: 1000,
        uncssrc: '.uncssrc',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)',
    };

uncss(files, options, function (error, output) {
    console.log(output);
});

/* Look Ma, no options! */
uncss(files, function (error, output) {
    console.log(output);
});

/* Specifying raw HTML */
var rawHtml = '...';

uncss(rawHtml, options, function (error, output) {
    console.log(output);
});

At build-time

UnCSS can also be used in conjunction with other JavaScript build systems, such as Grunt, Broccoli or Gulp!

From the command line

Usage: uncss [options] <file or URL, ...>
    e.g. uncss https://getbootstrap.com/docs/3.3/examples/jumbotron/ > stylesheet.css

Options:

  -h, --help                            output usage information
  -V, --version                         output the version number
  -i, --ignore <selector, ...>          Do not remove given selectors
  -m, --media <media_query, ...>        Process additional media queries
  -C, --csspath <path>                  Relative path where the CSS files are located
  -s, --stylesheets <file, ...>         Specify additional stylesheets to process
  -S, --ignoreSheets <selector, ...>    Do not include specified stylesheets
  -r, --raw <string>                    Pass in a raw string of CSS
  -t, --timeout <milliseconds>          Wait for JS evaluation
  -H, --htmlroot <folder>               Absolute paths' root location
  -u, --uncssrc <file>                  Load these options from <file>
  -n, --noBanner                        Disable banner
  -a, --userAgent <string>              Use a custom user agent string
  -I, --inject <file>                   Path to javascript file to be executed before uncss runs
  -o, --output <file>                   Path to write resulting CSS to

Note that you can pass both local file paths (which are processed by glob) and URLs to the program.

  • banner (boolean, default: true): Whether a banner should be prepended before each file block in the processed CSS.

  • csspath (string): Path where the CSS files are related to the HTML files. By default, UnCSS uses the path specified in the <link rel="stylesheet" href="path/to/file.css"/>.

  • htmlroot (string): Where the project root is. Useful for example if you have HTML that references local files with root-relative URLs, i.e. href="/css/style.css".

  • ignore (string[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors:

    /* uncss:ignore */
    .selector1 {
        /* this rule will be ignored */
    }
    
    .selector2 {
        /* this will NOT be ignored */
    }
    
    /* uncss:ignore start */
    
    /* all rules in here will be ignored */
    
    /* uncss:ignore end */
  • ignoreSheets (string[] | RegExp[]): Do not process these stylesheets, e.g. Google fonts. Accepts strings or regex patterns.

  • inject (string / function(window)): Path to a local javascript file which is executed before uncss runs. A function can also be passed directly in.

    Example inject.js file

    'use strict';
    
    module.exports = function (window) {
        window.document.querySelector('html').classList.add('no-csscalc', 'csscalc');
    };

    Example of passing inject as a function

    {
      inject: function(window){
        window.document.querySelector('html').classList.add('no-csscalc', 'csscalc');
      }
    }
  • jsdom (object) (Supported only by API): Supply the options used to create the JSDOM pages (https://github.com/jsdom/jsdom). At the moment, config.resources is not yet supported.

  • media (string[]): By default UnCSS processes only stylesheets with media query _all_, _screen_, and those without one. Specify here which others to include.

  • raw (string): Give the task a raw string of CSS in addition to the existing stylesheet options; useful in scripting when your CSS hasn't yet been written to disk.

  • report (boolean, default: true): Return the report object in callback.

  • strictSSL (boolean, default: true): Disable SSL verification when retrieving html source

  • stylesheets (string[]): Use these stylesheets instead of those extracted from the HTML files. Prepend paths with the file:// protocol to force use of local stylesheets, otherwise paths will be resolved as a browser would for an anchor tag href on the HTML page.

  • timeout (number): Specify how long to wait for the JS to be loaded.

  • uncssrc (string): Load all options from a JSON file. Regular expressions for the ignore and ignoreSheets options should be wrapped in quotation marks.

    Example uncssrc file:

    {
        "ignore": [".unused", "/^#js/"],
        "stylesheets": ["css/override.css"]
    }
  • userAgent (String, default: 'uncss'): The user agent string that jsdom should send when requesting pages. May be useful when loading markup from services which use user agent based device detection to serve custom markup to mobile devices. Defaults to uncss.

As a PostCSS Plugin

UnCSS can be used as a PostCSS Plugin.

postcss([require('uncss').postcssPlugin]);

See PostCSS docs for examples for your environment.

Note: Depending on your environment, you might not be able to use uncss as a PostCSS plugin since the plugin is not directly exported. In such cases, use the wrapper library postcss-uncss.

Options

  • html (string[]): provide a list of html files to parse for selectors and elements. Usage of globs is allowed.

  • ignore (string[] | RegExp[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors in your CSS:

    /* uncss:ignore */
    .selector1 {
        /* this rule will be ignored */
    }
    
    .selector2 {
        /* this will NOT be ignored */
    }
Example Configuration
{
  html: ['index.html', 'about.html', 'team/*.html'],
  ignore: ['.fade']
}

License

Copyright (c) 2019 Giacomo Martino. See the LICENSE file for license rights and limitations (MIT).

grunt-uncss's People

Contributors

addyosmani avatar alephyud avatar bezoerb avatar cvrebert avatar dependabot[bot] avatar dunckr avatar gltgrzegorz avatar javiercejudo avatar jmtavares avatar lgladdy avatar markbiesheuvel avatar readmecritic avatar sedovsek avatar sly777 avatar vseventer avatar xhmikosr avatar zlatanvasovic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-uncss's Issues

Note: new UnCSS callback signature

Hey!
UnCSS 0.8 will have the callback argument accept an error parameter, instead of just the result, to be more consistent with other APIs.

It won't be out until we test it some more, but just wanted to let you know this, in case grunt-uncss breaks when you update it!

Implement Support For Preprocessors?

Would it be possible to utilise something such as source maps and run the task against the built css and thus cleanup the SASS or LESS files?

This could then make maintaining "older" code bases easier to cleanup unnecessary CSS rules. Also, this could help maintain the cleanliness of the project going forward and prevent unnecessary builds only to then remove the unused output.

An alternative would be for a report of some sort to be generated of the styles and selectors that were removed so that a developer can then go back and remove these from the SASS or LESS files?

Ignore link rel="publisher"

In my HTML I have:

<link rel="publisher" href="https://plus.google.com/118384949211738083189">

uncss says:

Error: could not find: _scripts/https:/plus.google.com/118384949211738083189

:checked pseudo class being ignored?

I was essentially implementing a responsive menu exactly like this:
http://blog.lavoie.sl/2013/11/responsive-menu-in-pure-css.html

I found that the uncss version worked as expected with @media queries and everything, reducing the size of the stylesheet my huge amounts. But it seems to ignore the :checked pseudo selector that is crucial to make this hack work. If I use another pseudo like :focus, it gets included in the uncss. Strange.

I know it's a minor issue.

CC: @giakki
Really enjoying this plugin as a whole, it's what makes bootstrap viable for small projects to me.

Move "app" in "tests"?

I think it makes sense since it's used for testing. Also its uncss task should be moved to test too and not run when doing grunt.

Another thing, cssmin is pretty useless at this point too. Because after uncss is run, the output css is not minified. So cssmin should run after uncss.

newest version yields all sorts of incorrect results...

i pulled down the latest version and now the task does not execute correctly (whereas it had before this latest pull using the same exact configurations, etc)

  1. it's skipping classes that are clearly on the page. i have an element with class "modal" on it on a page going through uncss, but the modal css does not get carried over to the uncss stylesheet.
  2. it's ignoring hover rules. my rollover navigation is never hidden and shows at all times if i use the uncss stylesheet.
  3. the uncss stylesheet used to be 62kb large. now it's 29kb...

i'm sure there are more issues, but these were the most blatant.

Run uncss on multiple files

When I run uncss through a grunt task it concatenates the first into the second. Is this expected behavior? Ideally I would like to have two separate files uncss'd according to two seperate html files. Here is the part of the gruntfile:

uncss: {
dist: {
options: {
compress: true,
ignore: ['a.pdf']
},
files: {
'assets/css/global.css': ['index.html'],
'assets/css/home.css': ['home.html']
}
}
},

Remove compress option?

UnCSS removed the compress option (it is all @sindresorhus fault ;). I do see you are using cssmin. It is a good compressor, though I believe many devs have their own favorite minifier.

I can go either way, though I lean towards no minifer. But I wonder if it is more accurate/faster to lightly (non-aggressive) minify CSS first then reduces... hmmm...
I'm just opening this issue up for discussion.

Some CSS missing

I tried your project on my project, but found the output missing some CSS parts so the website output isn't correct.
Fork if you would like to test. Sorry I can't point to an error.

Can't get grunt-css to work

Hi.

I'm trying grunt-uncss with no success so far.

Running "uncss:dist" (uncss) task

C:\Users\xmr\Desktop\mpc-hc.org\node_modules\grunt-jekyll\node_modules\tmp\lib\tmp.js:261
  throw err;
        ^
mapReadFiles Error: could not find: C:\Users\xmr\Desktop\mpc-hc.org\_site\2012\06\21\welcome-to-the-new-website\_site\assets\css\pack-9c1b221d52ef3036ff1e34bf7ed3dce459533bf5.css

If I remove grunt-uncss everything works fine. I tried with and without specifying the stylesheet. If I skip it I end up with a zero byte tidy.css file and no errors.

My source is here https://github.com/mpc-hc/mpc-hc.org/tree/grunt-uncss

Any help is appreciated, thanks!

PS. The task order in Gruntfile is a little weird at the moment because I wanted to get this working first. I'll switch to concatenate, uncss, then cssmin later.

Implement support for delta between multiple files

Right now this implementation is limited to working against individual files. This works fine for simple pages but doesn't for the case where you have multiple pages sharing the same base css.

One possible solution:

  • Calculate the used CSS for each file
  • Merge the used CSS into a single file
  • Remove the duplicates

cc @stephenplusplus @sindresorhus @passy in case you guys have better ideas for how this problem might be solved.

Template engine and uncss

I have a express proyecto with jade as template engine.

could be possible to use uncss in my grunt config? I dont have html's files, only jade views, but the browser finally rendering html.

I'm trying do this but seems unlikely

Implement support for warnings on duplication across similar selectors

Used to identify duplication across modular CSS selectors. Possible scenario occurs with larger products and a team is responsible for each module.

.sports header {
    color: #333;
    font-weight: normal;
    font-size: 1.2em;
}

.politics header {
    color: #333;
    font-weight: normal;
    font-size: 1.2em;
}

A warning could be flagged and suggest a more abstract module applied. This might conflict with the use of mixins with pre-processors.

Tasks after uncss not run

In my Gruntfile I have:

    grunt.registerTask 'default', ['less', 'uncss', 'htmlbuild', 'htmlmin']

Tasks after uncss are not run.
A missing callback perhaps?

Can't install from npm (ENOENT, chmod)

$ npm install grunt-uncss --save-dev
npm http GET https://registry.npmjs.org/grunt-uncss
npm http 304 https://registry.npmjs.org/grunt-uncss
npm http GET https://registry.npmjs.org/underscore
npm http GET https://registry.npmjs.org/uncss
npm http 304 https://registry.npmjs.org/underscore
npm http 304 https://registry.npmjs.org/uncss
npm http GET https://registry.npmjs.org/commander
npm http GET https://registry.npmjs.org/css
npm http GET https://registry.npmjs.org/csso
npm http GET https://registry.npmjs.org/cheerio
npm http 304 https://registry.npmjs.org/commander
npm http 304 https://registry.npmjs.org/csso
npm http 304 https://registry.npmjs.org/css
npm http 304 https://registry.npmjs.org/cheerio
npm http GET https://registry.npmjs.org/css-parse/1.6.0
npm http GET https://registry.npmjs.org/css-stringify/1.3.2
npm http GET https://registry.npmjs.org/cheerio-select
npm http GET https://registry.npmjs.org/htmlparser2/3.1.4
npm http GET https://registry.npmjs.org/entities
npm http 304 https://registry.npmjs.org/css-stringify/1.3.2
npm http 304 https://registry.npmjs.org/css-parse/1.6.0
npm http 304 https://registry.npmjs.org/htmlparser2/3.1.4
npm http 304 https://registry.npmjs.org/cheerio-select
npm http 304 https://registry.npmjs.org/entities
npm http GET https://registry.npmjs.org/CSSselect
npm http GET https://registry.npmjs.org/domhandler
npm http GET https://registry.npmjs.org/domutils
npm http GET https://registry.npmjs.org/domelementtype
npm http GET https://registry.npmjs.org/readable-stream
npm http 304 https://registry.npmjs.org/domutils
npm http 304 https://registry.npmjs.org/domhandler
npm http 304 https://registry.npmjs.org/domelementtype
npm http 304 https://registry.npmjs.org/CSSselect
npm http 304 https://registry.npmjs.org/readable-stream
npm http GET https://registry.npmjs.org/CSSwhat
npm http 304 https://registry.npmjs.org/CSSwhat
npm ERR! Error: ENOENT, chmod '/Users/nickp/code/project/node_modules/grunt-uncss/node_modules/uncss/node bin/index.js'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <[email protected]>

npm ERR! System Darwin 13.0.0
npm ERR! command "/usr/local/Cellar/node/0.10.22/bin/node" "/usr/local/bin/npm" "install" "grunt-uncss" "--save-dev"
npm ERR! cwd /Users/nickp/code/project
npm ERR! node -v v0.10.22
npm ERR! npm -v 1.3.14
npm ERR! path /Users/nickp/code/project/node_modules/grunt-uncss/node_modules/uncss/node bin/index.js
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/nickp/code/project/npm-debug.log
npm ERR! not ok code 0

I can install all my other NPM packages fine.

Could this perhaps be a problem with the space in node bin?

Support alternative search path in usemin markup

I'm having issues with the basic markup provided as part of yo webapp:

        <!-- build:css(.tmp) styles/main.css -->
        <link rel="stylesheet" href="styles/main.css">
        <!-- endbuild -->

I'm not familiar enough with Grunt plugins to fix this one just yet. grunt-contrib-cssmin seems to respect the alternate search path.

grunt uncss fails with warning

Error:
2014-01-15 16:41:47.276 phantomjs[1995:507] *** WARNING: Method userSpaceScaleFactor in class NSView is deprecated on 10.7 and later. It should not be used in new applications. Use convertRectToBacking: instead.

While building with uncss the task bombs out with this warning.

Feature: support for glob patterns

Currently, using glob patterns will cause the task to fail with:

Running "uncss:dist" (uncss) task
Fatal error: Unable to write "dist/styles/{,*/}*.css" file (Error code: undefined).

Task:

uncss: {
  dist: {
    files: {
      'dist/styles/{,*/}*.css': ['dist/{**,}*.html']
    }
  }
}

weird error in combination with grunt-contrib-compass and foundation scss

When trying to cleanup a css file generated with grunt-contrib-compass where foundation is included i get some weird error:

Running "uncss:dist" (uncss) task

node_modules/grunt-contrib-compass/node_modules/tmp/lib/tmp.js:261
  throw err;
        ^
TypeError: Cannot convert null to object

here are the file contents of main.scss:

@import "../bower_components/foundation/scss/foundation";

.hero-unit {
    margin: 0 auto;

}

Buggy with ember.js

I can't get uncss to work completely with ember. Some styles are used and some get totally ignored. Any ideas on how to fix this?

    uncss: {
            dist: {
                files: {
                    '<%= yeoman.dist %>/styles/main.css': [
                        '<%= yeoman.dist %>/index.html',
                        '<%= yeoman.app %>/templates/{,*/}*.hbs'
                    ]
                }
            },
            options: {
                compress: true
            }
        }

Errors on OS X from deprecated method being used by uncss in PhantomJS

The PhantomJS dependency used by the uncss is causing errors on some later versions of OS X from a deprecated method being used by PhantomJS:

Running "uncss:main" (uncss) task
2014-01-07 22:49:02.381 phantomjs[7283:507] *** WARNING: Method userSpaceScaleFactor in class NSView is deprecated on 10.7 and later. It should not be used in new applications. Use convertRectToBacking: instead.

Once uncss is able to upgrade its PhantomJS version, grunt-uncss should be able to update its uncss version and resolve this error.

I currently have an issue open on uncss for this as well:

uncss/uncss#21

Ignore option not working

Hi there,

I've not been able to get the ignore option to work. The following does remove unused css, but it it is neither compressed nor does the ignore rule work. Am I doing something wrong?

Thanks.

uncss: {
dist: {
files: {
'dist/css/app.css': ['index.html']
}
},
options: {
ignore: ['.removeDivs', '.nav', '#navigation', '.active'],
compress: true
}
},

Regex Support

As of version 0.6.0 uncss supports regular expressions for ignoring selectors.
Can you update the version in your package.json?
Thanks

Alternative to ignore | Keeping some CSS

Using grunt-processhtml (https://github.com/dciccale/grunt-processhtml) you can add elements to your html file that could be added in later, but have them stay safe with uncss.

run uncss on html file first, then run processhtml.

using the build:remove comments, processhtml will remove the code in-between the comments.

    <!-- build:remove -->
    <div class="box"></div>
    <!-- /build -->

would prevent .box {} from being removed by uncss, even if it doesn't appear elsewhere in the html file.

Running with local virtualhost (using Laravel)

Runs fine when I use the source's command line tool (https://github.com/giakki/uncss) :

({project} just for privacy)

uncss http://{project}.dev > public/assets/css/style.uncss.css

When trying to run it through grunt-uncss I get a :

Destination (public/assets/css/style.uncss.css) not written because src files were empty.

I'm using load-grunt-tasks and load-grunt-config, could that cause an issue?

Here's my uncss.js task file:

module.exports = {
  dist: {
    files: {
      'public/assets/css/style.uncss.css': ['http://{project}.dev/']
    }
  }
};

Thanks in advance, can't wait to use this in production ๐Ÿ‘

Improve documentation

  • How can grunt-uncss be used
  • What are the limitations of the project
  • Where is this particularly useful?

by default, media="print" stylesheets are included

after trying it out, the CSS was indeed smaller (a non-CSS framework site's file from 78kb to 63kb) ...but some things were hidden and i couldn't figure out why at first...then i noticed that my print styles were included in the main stylesheet!

might i suggest ignoring media="print" by default, and having an option to include it if you want to (although i don't know why you would...)

thanks!

// interpreted as a relative path instead of an http one

I have references to FontAwesome, but it's not explicitly specifying a protocol. uncss is not recognizing it unless I manually force it as http:// instead.

<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

timeout not working

The outputted CSS is missing a lot of styles... They seem to all be related to an area of the page that does a fair amount of DOM manipulation on page load. I've set the timeout option but it doesn't fix the issue. Any ideas?

Thank!

Strange error using node 0.10.22 and phantomjs 1.9.2

Thanks for maintaining this excellent project! I'm just now playing around with it and found that when I'm using node 10.22 and phantomjs 1.9.2 I get the following error

Running "uncss:dist" (uncss) task
2013-12-31 16:49:38.963 phantomjs[16119:507] *** WARNING: Method userSpaceScaleFactor in class NSView is deprecated on 10.7 and later. It should not be used in new applications. Use convertRectToBacking: instead.

Here is my Gruntfile if that helps (not sure if this is a pure phantom problem or if something else is in the mix)

module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-uncss');

  grunt.initConfig({
    uncss: {
      dist: {
        files: {
          'website/static/css/tidy.css': ['website/templates/index.html']
          }
        }
    },
    processhtml: {
      dist: {
        files: {
          'website/static/dist/index.html': ['website/templates/index.html']
        }
      }
    }

Ability to check against http URL?

The way it works now would only work with static html pages with link tags. I don't see it working with inline css that uses @import (Though I am considering to remove @import from this legacy code 'cause it is blocking) Still, I am unable to get this working with a list of php files with a structure like index, includes/head.php, and includes/body.php. I think the only way to have it working against dynamic pages would be through remote checking. What do you think? Maybe the PhantomJS solution you are talking about in the doc would be better, but I am not sure.

ability to use w/template includes

this is a great idea, but unfortunately i can't use it on any of my projects because i normally don't code out html templates in .html files....i usually use .net or php includes. do you think it'll be possible at some point to extend it so it'll work with includes? thanks!

No errors and no output file

After running uncss I have no errors on the console but, the output file is also not written. I know if the sources are empty it will not write the output file but, that is not the case here.

Here is the verbose output from the task:

Running "uncss:dev" (uncss) task
Verifying property uncss.dev exists in config...OK
Files: dxr/templates/error.html, dxr/templates/file.html, dxr/templates/folder.html, dxr/templates/layout.html, dxr/templates/search.html, dxr/templates/partial/filter.html -> dxr/static/css/dist/dxr.css
Options: compress=false, ignore=[""], stylesheets=["dxr/static/css/dxr.css","dxr/static/css/code-style.css"]
2014-01-08 20:42:51.134 phantomjs[45411:507] *** WARNING: Method userSpaceScaleFactor in class NSView is deprecated on 10.7 and later. It should not be used in new applications. Use convertRectToBacking: instead.

Now, one thing to note is that the app is a Flask (Python) app if that makes a difference....

TypeError: Cannot convert undefined or null to object

First and foremost, great work on this Grunt task, I love the idea!

Unfortunately, I keep getting this TypeError: "Cannot convert undefined or null to object". My config in Gruntfile.js looks as follows:

uncss: {
    dist: {
        files: {
            '_build/css/tidy.css': ['_build/index.html']
        },
        options: {
            compress: true
        }
    }
}

Anyone else run into this error yet?

PS I'm using version 0.5.3

if html file > 31kb, Fatal error: spawn ENAMETOOLONG

so i finally got this up and running, and got "Fatal error: spawn ENAMETOOLONG" specifically why i tried to include two files into the source. after troubleshooting a bit, it seemed to only come up if the html filesize was larger than 31kb. it didn't matter which lines i deleted from the html files, as long as i kept the filesize 31kb or smaller it worked.

why is that? does there have to be a limit on filesize? sure 31kb might be a good limit to shoot for, but sometimes larger files are unavoidable...

doesn't work with html files in different directories

Hello,
After trying many different options, I can't get this to work.

I'm running a jekyll site with a structure like this

  • css
  • index.html
    • folder1/index.html
      • folder1/foldera/index.html
    • folder2/index.html
  • ...

The problem seem to be that uncss tries to look for a css file in the wrong folder (and not in the root css/ folder) when the html file is in a subfolder, see this config:

uncss: {
      dist: {
        files: {
          '_site/css/bootstrap.custom.min.css': ['_site/index.html', '_site/competences/index.html']
        }
      }
    }

and error:

Running "uncss:dist" (uncss) task
Fatal error: UnCSS: could not open/Users/dgbrt/Dropbox/developpement/dgbrt.fr/_site/competences/css/bootstrap.custom.min.css

I saw this issue with a similar problem (it seems) but couldn't find a solution regardless.
#46

uncss fails due to cdn path

uncss fails when hitting a cdn css path

Steps to reproduce

Add a url to a cdn based css resource in your html page:
//cdnjs.cloudflare.com/ajax/libs/topcoat-icons/0.2.0/font/icomatic.css
notice // to allow for http & https loading

Run uncss against this page

Expected

Uncss will recognize external resources and either load and export processed css
OR
skip and move on without error

Actual

uncss errors with message:
`Fatal error: mapReadFiles Error: could not find: /cdnjs.cloudflare.com/ajax/libs/topcoat-icons/0.2.0/font/icomatic.css'
It assumes a local file path instead of recognizing it as an external resource.

grunt-cssrazor

Hi,

Did you look into github.com/changer/grunt-cssrazor. I think we're doing practically the same, anything you can learn from my project, should I abandon my project in favor of yours? Would happily do so!

Fatal error: missing '{' near line 2:16

This error has only popped up recently, and I noticed if I replaced uncss.js with an older version it corrected the issue. I'll see if I can compare the two to find out what the exact issue is.

Should ignore outer css source

I use google font in my project, unfortunately, it will cause error report when I operate grunt-uncss task.

Error: could not find: build\http:\fonts.googleapis.com\css?family=Caudex

PHP Support

It would be fantastic if uncss could in the future support scanning PHP files, currently the task fails when any PHP tag is found, simply ignoring these tags would probably work! For a lot of development situations this would be enormously useful.

Thanks :)

[SyntaxError: Unmatched selector: (http]

I got the following error when using uncss:

Running "uncss:dist" (uncss) task
[SyntaxError: Unmatched selector: (http]
>> Uncssing source "docs/index.html" failed.
Warning: Uncss failed.๏ฟฝ Use --force to continue.

Aborted due to warnings.

This is my package.json:

{
  "name": "ExampleApp",
  "version": "0.0.1",
  "private": true,
  "devDependencies": {
    "grunt": "~0.4.2",
    "grunt-cli": "~0.1.11",
    "grunt-uncss": "~0.1.5",
    "grunt-processhtml": "~0.2.7"
  }
}

And this is my Gruntfile.js:

module.exports = function(grunt) {
    grunt.initConfig({

        uncss: {
            dist: {
                files: {
                    'docs/tidy.css': ['docs/index.html']
                }
            },
            options: {
                compress:true,
            }
        },

        processhtml: {
            dist: {
                files: {
                    'docs/new/index.html': ['docs/index.html']
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-uncss');
    grunt.loadNpmTasks('grunt-processhtml');

    grunt.registerTask('default', ['uncss','processhtml']);

};

Can you please elaborate on why I'm getting this error?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.