GithubHelp home page GithubHelp logo

webpack-contrib / purifycss-webpack Goto Github PK

View Code? Open in Web Editor NEW
773.0 24.0 37.0 138 KB

UNMAINTAINED, use https://github.com/FullHuman/purgecss-webpack-plugin

License: MIT License

JavaScript 100.00%
webpack-plugin purifycss

purifycss-webpack's Introduction

UNMAINTAINED

Please use: https://github.com/FullHuman/purgecss-webpack-plugin


npm deps test coverage quality chat

PurifyCSS Plugin

PurifyCSS for Webpack.

This plugin uses PurifyCSS to remove unused selectors from your CSS. You should use it with the extract-text-webpack-plugin.

Without any CSS file being emitted as an asset, this plugin will do nothing. You can also use the file plugin to drop a CSS file into your output folder, but it is highly recommended to use the PurifyCSS plugin with the Extract Text plugin.

This plugin replaces earlier purifycss-webpack-plugin and it has a different API!

Install

npm i -D purifycss-webpack purify-css

Usage

Configure as follows:

const path = require('path');
const glob = require('glob');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');

module.exports = {
  entry: {...},
  output: {...},
  module: {
    rules: [
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          fallbackLoader: 'style-loader',
          loader: 'css-loader'
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('[name].[contenthash].css'),
    // Make sure this is after ExtractTextPlugin!
    new PurifyCSSPlugin({
      // Give paths to parse for rules. These should be absolute!
      paths: glob.sync(path.join(__dirname, 'app/*.html')),
    })
  ]
};

And, that's it! Your scripts and view files will be scanned for classes, and those that are unused will be stripped off your CSS - aka. "purified".

In order to use this plugin to look into multiple paths you will need to:

  1. npm install --save glob-all
  2. Add const glob = require('glob-all'); at the top of your webpack config
  3. Then you can pass your paths to an array, like so:
paths: glob.sync([
  path.join(__dirname, '.php'),
  path.join(__dirname, 'partials/.php')
]),

You can pass an object (<entry> -> [<absolute path>]) to paths if you want to control the behavior per entry.

Options

This plugin, unlike the original PurifyCSS plugin, provides special features, such as scanning the dependency files. You can configure using the following fields:

Property Description
styleExtensions An array of file extensions for determining used classes within style files. Defaults to ['.css'].
moduleExtensions An array of file extensions for determining used classes within node_modules. Defaults to [], but ['.html'] can be useful here.
minimize Enable CSS minification. Alias to purifyOptions.minify. Disabled by default.
paths An array of absolute paths or a path to traverse. This also accepts an object (<entry name> -> <paths>). It can be a good idea glob these.
purifyOptions Pass custom options to PurifyCSS.
verbose Set this flag to get verbose output from the plugin. This sets purifyOptions.info, but you can override info separately if you want less logging.

The plugin does not emit sourcemaps even if you enable sourceMap option on loaders!

Usage with CSS Modules

PurifyCSS doesn't support classes that have been namespaced with CSS Modules. However, by adding a static string to css-loader's localIdentName, you can effectively whitelist these namespaced classes.

In this example, purify will be our whitelisted string. Note: Make sure this string doesn't occur in any of your other CSS class names. Keep in mind that whatever you choose will end up in your application at runtime - try to keep it short!

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              options: {
                localIdentName: 'purify_[hash:base64:5]',
                modules: true
              }
            }
          ]
        })
      }
    ]
  },
  plugins: [
    ...,
    new PurifyCSSPlugin({
      purifyOptions: {
        whitelist: ['*purify*']
      }
    })
  ]
};

Maintainers


Juho Vepsäläinen

Joshua Wiens

Kees Kluskens

Sean Larkin

purifycss-webpack's People

Contributors

andrew avatar bebraw avatar codyreichert avatar evilebottnawi avatar iam4x avatar johakr avatar joshwiens avatar jportegijs avatar kennyt avatar rahavlussato avatar sapegin avatar t47io avatar vpr99 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

purifycss-webpack's Issues

css.charAt is not a function

I have such error when trying to use the plugin.

Here’s how I’ve set up the CSS loaders:

      {
        test: /\.styl$/,
        include: paths.appSrc,
        exclude: paths.appComponents,
        loader: ExtractTextPlugin.extract(
          ['style'],
          [
            'css?importLoaders=1',
            'postcss',
            'stylus'
          ]
        )
      },
      {
        test: /\.styl$/,
        include: paths.appComponents,
        loader: ExtractTextPlugin.extract(
          ['style'],
          [
            'css?modules&importLoaders=1&localIdentName=[folder]__[local]___[hash:base64:5]',
            'postcss',
            'stylus',
          ]),
      },
      {
        test: /\.(woff|woff2).css$/,
        include: paths.appSrc,
        loader: 'file',
        query: {
          name: 'static/css/[name].[ext]'
        }
      }

First and second are for processing Stylus styles and CSS modules, the third is just to move CSS containing base64 encoded WOFF(2) fonts into build dir.

Here’s the setup of ExtractTextPlugin:

new ExtractTextPlugin('static/css/[name].[contenthash:8].css')

And finally the PurifyPlugin:

    new PurifyPlugin({
      // Give paths to parse for rules. These should be absolute!
      paths: glob.sync(`${paths.appSrc}/*`),
      extensions: ['.html', '.jsx'],
      purifyOptions: {
        info: true,
        rejected: true
      }
    })

I’ve tried a lot of ways to specify the paths, like in README, like in examples, by absolute paths (/User/…), but no luck.

I’ve updated the plugin and Webpack, but it also doesn’t help.

Any help and ideas about what could go wrong?

CSS + SCSS configuration

I load both .css and .scss as

{ test: /\.scss$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader"), include: paths, },
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader"), include: paths }, ]

Now when i apply PurifyCss plugin, it does not include any style from any of .scss files. (works as expected for .css files). When i remove purify plugin, styles from .scss files are loaded.

Use multiple files

Hey.

I just figured out, with a huge facedesk involved, that there is a PurifyCSS plugin for WebPack. Previously, I used the following script to test out what actually happens when I run PurifyCSS - and the result is so drastic that I want to use it. here is the script, as I have it:

var purify = require("purify-css");
var fs = require("fs");
var css = fs.readFileSync(process.argv[2], "utf8");
var merge = require("array-merger").merge;
var glob = require("glob").sync;
var path = require("path");

var paths = [
    // Templates
    "protected/views/*/*.php",
    "protected/components/views/*.php",
    "protected/modules/*/views/*/*.php",
    "protected/modules/*/components/views/*.php",
    "themes/dragonsinn/views/layouts/*.php",
    "protected/extensions/*/components/views/*.php",
    // JavaScript + OJ
    "web-lib/*.js",
    "web-lib/*.oj",
    "protected/extensions/*/js/*.js",
    // Specific
    "protected/modules/chat/js/*.js",
    "protected/modules/chat/lib/template/*.html",
    "protected/modules/chat/lib/template/*.php",
    "protected/modules/chat/views/*/*.php"
];

var files=[];
paths.forEach(function(p){
    files = merge(files,glob(p));
});

console.log("Target:", process.argv[2]);

purify(files, css, {
    minify: true,
    info: true
}, function(output){
    fs.writeFileSync(
        path.join(
            path.dirname(process.argv[2]),
            "purified-"+path.basename(process.argv[2])
        ), output
    );
});

I get an "1.9 times smaller" message - and that is insane. So I want to use this with WebPack. However, the code and README do not indicate how I would pass multiple files into the plugin - and, if I can savely use ExtractTextPlugin as I am already doing.

So how would I go about oding this? :)

PurifyCSS has reduced the file size by ~0.0%

I am having trouble getting it working. My config:

   new ExtractTextPlugin({
         filename: cssOutput,
         disable: false,
         allChunks: true
      }),


      /**
       * Plugin: PurifyCSS WebPack Plugin
       * Description: This is a plugin for WebPack that utilizes PurifyCSS to clean your CSS. Its dead simple, but it requires you to be prepared.
       *
       * See: https://github.com/purifycss/purifycss-webpack-plugin
       */

      new PurifyCSSPlugin({
         basePath: helpers.paths.root,
         paths: [
            "/src/app-components/**/*.template.html",
            "/src/app-components/**/*.component.ts",
         ],
         purifyOptions: {
            minify: true,
            info: true,
            output: 'wwwroot/css/purified',
            rejected: true,
            // whitelist: []

         }
      }),

I modified the plugin so it tells me which css assets it detects. It finds 2 css bundles as it should. But then it does nothing to them.

Hello purifyCSS-webpack-plugin
Happy[js]: Version: 2.1.3. Using cache? no. Threads: 5 (shared pool)
Happy[js]: All set; signalling webpack to proceed.
Checking for purifyable CSS.
We found a CSS. So purify it.
/css/app.style.css?43b887ad5e2f64648285
We found a CSS. So purify it.
##################################
/css/vendors.style.css?43b887ad5e2f64648285
PurifyCSS has reduced the file size by ~0.0%
##################################
This function took:  3134 ms
##################################
Rejected selectors:

##################################
##################################
PurifyCSS has reduced the file size by ~0.0%
##################################
This function took:  1951 ms
##################################
Rejected selectors:

##################################

Why is it not purifying them?

plugin no effect with my css, sass loaders

Hi,

I use loader
extractCSS.extract([ 'css', 'sass' ])

And in my plugins I add

new purify({
    basePath: __dirname + '../',
    paths: [
      'index.html'
    ]
  })

When I build my app without purifycss plugin my css i builded and minified but when I put purifycss plugin as above, so my css is well extracted to an build.css file but two problem : it isn't minified and the big problem is my unused class are still here, no change effect!

thanks in advance

Webpack2 support

First of all, thank for the plugin!

Does it support webpack2 officially?
I got 'unmet peer dependency' npm warning when install the plugin together with webpack2.

└── UNMET PEER DEPENDENCY [email protected]

npm WARN [email protected] requires a peer of webpack@^1.9.11 but none was installed.

V2.0.3 paths per entry fails.

paths: {
          desktop: glob.sync(`${PATH_SRC_DESKTOP}/**/*`),
          mobile: glob.sync(`${PATH_SRC_MOBILE}/**/*`),
        },

Error:

/Users/linken/Coding/project/node_modules/purifycss-webpack-plugin/index.js:33
        var files = self.paths.reduce(function(results, p) {
                               ^
TypeError: self.paths.reduce is not a function
    at Compiler.<anonymous> (/Users/linken/Coding/project/node_modules/purifycss-webpack-plugin/index.js:33:32)
    at Compiler.applyPlugins (/Users/linken/Coding/project/node_modules/tapable/lib/Tapable.js:61:14)
    at Compiler.newCompilation (/Users/linken/Coding/project/node_modules/webpack/lib/Compiler.js:430:7)
    at /Users/linken/Coding/project/node_modules/webpack/lib/Compiler.js:464:26
    at Compiler.applyPluginsAsyncSeries (/Users/linken/Coding/project/node_modules/tapable/lib/Tapable.js:131:46)
    at Compiler.compile (/Users/linken/Coding/project/node_modules/webpack/lib/Compiler.js:459:7)
    at /Users/linken/Coding/project/node_modules/webpack/lib/Compiler.js:220:10
    at Compiler.readRecords (/Users/linken/Coding/project/node_modules/webpack/lib/Compiler.js:369:10)
    at /Users/linken/Coding/project/node_modules/webpack/lib/Compiler.js:217:9
    at next (/Users/linken/Coding/project/node_modules/tapable/lib/Tapable.js:138:11)
    at Compiler.compiler.plugin (/Users/linken/Coding/project/node_modules/webpack/lib/CachePlugin.js:35:59)
    at Compiler.applyPluginsAsyncSeries (/Users/linken/Coding/project/node_modules/tapable/lib/Tapable.js:142:13)
    at /Users/linken/Coding/project/node_modules/webpack/lib/Compiler.js:214:8
    at next (/Users/linken/Coding/project/node_modules/tapable/lib/Tapable.js:138:11)
    at Compiler.compiler.plugin (/Users/linken/Coding/project/node_modules/webpack/lib/node/NodeEnvironmentPlugin.js:21:4)
    at Compiler.applyPluginsAsyncSeries (/Users/linken/Coding/project/node_modules/tapable/lib/Tapable.js:142:13)
    at Compiler.run (/Users/linken/Coding/project/node_modules/webpack/lib/Compiler.js:211:7)
    at processOptions (/Users/linken/Coding/project/node_modules/webpack/bin/webpack.js:358:12)
    at Object.<anonymous> (/Users/linken/Coding/project/node_modules/webpack/bin/webpack.js:362:1)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:420:7)
    at startup (bootstrap_node.js:139:9)
    at bootstrap_node.js:535:3

example build error

I git clone your repo and cd examples && npm i && npm run build
Got this error:

module.js:472
    throw err;
    ^

Error: Cannot find module '../'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/jeggett/test/purifycss-webpack/examples/webpack.parts.js:2:25)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)

Maybe this line const PurifyCSSPlugin = require('../'); from webpack.config.js caused that?

React / Webpack app

Hi!
Trying to config this in my project, and so far no effect on css, and no output during build. Here's my webpack config:

new ExtractTextPlugin('bundle.css'),
new purifycss({
  basePath: path.join(__dirname, '../src'),
  resolveExtensions: ['.html', '.js'],
  paths: [
    '../src/**/*.js',
    'index.html',
  ],
  purifyOptions: {
    minify: true,
    info: true,
    rejected: true,
 }

Tried with just __dirname as basePath, tried without paths, still no output and my bundle.css stays the same. What am I doing wrong?

Could you provide me a demo?

First of all , thanks for your plugin. While I try the plugin together with the 'LESS' and 'html-webpack-plugin' some times , but failed.
Could you help me with giving a more detail demo ? Cheers.

css modules + purifycss plugin = no css

Hey :)

I've been trying to use css modules and the purifycss plugin but with no luck :(
I am using webpack2 and extract-text-webpack-plugin.

webpack config:

{
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({loader:"css-loader?minimize&modules&importLoaders=1"}),
},
...
plugins: [
  new ExtractTextPlugin({
      filename: "style.css",
      allChunks: true
    }),
  new purifyCSS({
     basePath: path.resolve(__dirname, 'static')
})

result:

   style.css  0 bytes          [emitted] 

Can somebody help me with this?
All that I want is that style.css to have just the classes I use, not all of them.

Thank you!

Example with `.js/.jsx` files?

I'm trying to use PurifyCSS but without luck, I don't have an index.html entry file since it's an SPA bundled by webpack.

new PurifyCssPlugin(path.join(__dirname, '../app'), '/index.js') ?

My CSS build has the same size, ideas?

Removing used css

So I have the following css:

body {
  display: -ms-flexbox;
  display: flex;
  background-color: deeppink; }
  body div {
    background-color: deepskyblue; }

p {
  background-color: lime; }

Which after purifying is looking like this:

body {
  display: -ms-flexbox;
  display: flex;
  background-color: deeppink;
}

p {
  background-color: lime;
}

I am running with webpack 2 with the following options:

new Purify({
        basePath: __dirname,
        paths: ['index.html']
})

Purified build does not match unpurified one

To debug I simply included all my relevant files into the paths:

new PurifyPlugin({
        moduleExtensions: [
          '.html',
          '.pug',
          '.js',
          '.jsx',
          '.ts',
          '.tsx',
        ],
        paths: glob.sync(`${PATH_SRC}/**/*.{js,jsx,ts,tsx,html,pug}`),
        purifyOptions: {
          info: true,
          minify: true,
          rejected: false,
        },
        styleExtensions: [
          '.css',
          '.less',
          '.sass',
          '.scss',
          '.styl',
        ],
      })

The css is then purified, but it looks like it's missing styles when I launch it in the browser.

Handlebars Compatibility

Not sure if this is the right place to file this issue, perhaps the main purifycss repository is more appropriate, but anyway. I'm trying to use this plugin together with some Handlebars templates, like so:

new PurifyCSSPlugin({
    basePath: __dirname,
    resolveExtensions: ['.hbs'],
    paths: ['resources/assets/views/*.hbs'],
    purifyOptions: {
        rejected: true
    }
})
...
<body>
  <main class="wrapper">
    <nav class="navigation" id="main-navigation">
    </nav>
...

But no luck. All css rules are removed (e.g. .wrapper, .navigation) and I end up with an empty file. Does this plugin only work for HTML files?

Not all classes being purified.

Hi there,

I'm using the latest version of this plugin in conjunction with ExtractTextPlugin, it's executing fine, but isn't minifying as much as I would have expected.

For example, I have a typical bootstrap grid system component, with all the grid classes, .col-xs-3, .col-md-offset-1, .col-lg-push-11 etc. Not a single one is being removed, and I can search my codebase, and find no references to them.

My config:

        // Remove unused CSS styles
        new PurifyPlugin({
            basePath: config.app,
            paths: [
                "templates/**/*.html",
                "scripts/views/**/*.js",
                "scripts/*.js",
                "../../core/templates/**/*.html",
                "../../core/scripts/views/**/*.js"
            ],
            purifyOptions: {
                minify: true,
                info: true,
                rejected: true
            }
        }),

With paths as an empty array : 8.2% reduction
With paths as above: 4.2% reduction

i.e. the files specified by paths account for that 4% difference.

To clarify, is the paths option only for additional templates/views that webpack wouldn't be aware of from tracing the apps dependency tree and bundling?

As the grid styles are the basic bootstrap grid system, I see it's in various node_modules packages docs, is there any chance purify is getting lost looking in there and counting those?

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.