Gulp - How to remove duplicated styles in individual css files, If they have already present in common css file - TagMerge
4Gulp - How to remove duplicated styles in individual css files, If they have already present in common css fileGulp - How to remove duplicated styles in individual css files, If they have already present in common css file

Gulp - How to remove duplicated styles in individual css files, If they have already present in common css file

Asked 1 years ago
0
4 answers

You should think of compiling-merging both your files into one 'main' css file where you could clean-minify-etc.

As there is no 'real gain' of removing duplicated of both files if they arent being used on the same page.

And if they are being used a the same page, could use a minified-merged css file, you would also reduce the amount of blocking calls to render your page as well.

Can concatenate your css files with gulp-concat :

var concat = require('gulp-concat');
 
gulp.task('concat-css', function() {
  return gulp.src('./*.css')
    .pipe(concat('main.css'))
    .pipe(gulp.dest('dist'));
});

Can remove duplicates using clean-css or gulp-clean-css wrapper :

gulp.task('minify-css', () => {
  return gulp.src('dist/*.css')
    .pipe(cleanCSS({removeDuplicateRules: 'true'}))
    .pipe(gulp.dest('dist'));
});

So you could end up calling concat-css first, then minify-css and would have a main.css file ready to use without duplicate.

Source: link

0

Here is the syntax of CLI command:
purgecss --css <css file> --content <content file to parse css> --out <output-directory>
Since Purgecss is installed in /node_modules we must run this command through npm script. We use --out dist option to store output CSS files in dist folder after transformed. Now change the path of bootstrap-grid.min.css in index.html to:
<link rel="stylesheet" href="./dist/bootstrap-grid.min.css" />
In my index.js file, I simply import bootstrap grid CSS.
// Import CSS Grid min CSSimport 'bootstrap/dist/css/bootstrap-grid.min.css'
To use Purgecss with Webpack simply install this Webpack plugin:
npm i purgecss-webpack-plugin -D

Source: link

0

Installation
npm install -g uncss
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);
});
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
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 */
Example inject.js file
'use strict';

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

Source: link

0

I'm trying to use the preprocess function to remove duplicates in the css, but the context.parsedStylesheets seems unchanged when using it. should this be an option in the package itself? I've made a PR about this, since this doesn't work in the gulpfile..
preprocess: function(context, template, Handlebars) {
  return new Promise(function(resolve, reject) {
    var stylesheets = context.stylesheets.map(function(file) {
      return path.join(process.cwd(), 'bin' || '.', file);
    });

    livingcss.utils
      .readFiles(stylesheets, function(data) {
        context.parsedStylesheets = context.parsedStylesheets || [];
        context.parsedStylesheets.push(livingcss.utils.fixSVGIssue(data));
      })
      .then(function() {
        var allCSS = context.parsedStylesheets
          .map(function(stylesheet) {
            return stylesheet;
          })
          .join('\n');
        var allDedupedCSS = new CleanCSS({ level: 2 }).minify(allCSS);

        context.parsedStylesheets = [allDedupedCSS.styles];

        if (allDedupedCSS.errors.length !== 0) {
          reject(allDedupedCSS.errors.join('\n'));
        }
      })
      .then(function() {
        Handlebars.registerHelper('global', function(key) {
          return lernaCfg[key];
        });
        // register a glob of partials with Handlebars
        livingcss.utils
          .readFileGlobs('./template/partials/*.hbs', function(data, file) {
            // make the name of the partial the name of the file
            const partialName = path.basename(file, path.extname(file));
            Handlebars.registerPartial(partialName, data);
          })
          .then(function() {
            resolve();
          })
          .catch(function(e) {
            console.log(e);
            reject(e);
          });
      });
  });
}

Source: link

Recent Questions on css

    Programming Languages