Skip to content

Commit 5900e0c

Browse files
committed
Add options (and some flexibility) to the plugin
Add info to README
1 parent 46f115e commit 5900e0c

File tree

3 files changed

+124
-29
lines changed

3 files changed

+124
-29
lines changed

README.md

+42
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,45 @@
11
# Optimize CSS Assets Webpack Plugin
22

33
A Webpack plugin to optimize \ minimize CSS assets.
4+
5+
## What does the plugin do?
6+
7+
It will search for CSS assets during the Webpack build and will optimize \ minimize the CSS (by default it uses [cssnano](http://github.com/ben-eb/cssnano) but a custom css processor can be specified).
8+
9+
### Solves [extract-text-webpack-plugin](http://github.com/webpack/extract-text-webpack-plugin) CSS duplication problem:
10+
11+
Since [extract-text-webpack-plugin](http://github.com/webpack/extract-text-webpack-plugin) only bundles (merges) text chunks, if its used to bundle CSS, the bundle might have duplicate entries (chunks can be duplicate free but when merged, duplicate CSS can be created).
12+
13+
## Configuration:
14+
15+
The plugin can receive the following options (all of them are optional):
16+
* assetNameRegExp: A regular expression that indicates the names of the assets that should be optimized \ minimized, defaults to `/\.css$/g`
17+
* cssProcessor: The css processor used to optimize \ minimize the CSS, defaults to [cssnano](http://github.com/ben-eb/cssnano). This should be a function that follows cssnano.process interface (receives a css and options parameters and returns a Promise).
18+
* cssProcessorOptions: The options passed to the cssProcessor, defaults to `{}`
19+
* canPrint: A boolean indicating if the plugin can print messages to the console, defaults to `true`
20+
21+
## Example:
22+
23+
``` javascript
24+
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
25+
module.exports = {
26+
module: {
27+
loaders: [
28+
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
29+
]
30+
},
31+
plugins: [
32+
new ExtractTextPlugin("styles.css"),
33+
new OptimizeCssAssetsPlugin({
34+
assetNameRegExp: /\.optimize\.css$/g,
35+
cssProcessor: require('cssnano'),
36+
cssProcessorOptions: { discardComments: {removeAll: true } },
37+
canPrint: true
38+
})
39+
]
40+
}
41+
```
42+
43+
## License
44+
45+
MIT (http://www.opensource.org/licenses/mit-license.php)

index.js

+81-28
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,104 @@
11
var _ = require('underscore');
2-
var cssnano = require('cssnano');
32

4-
function OptimizeCssAssetsPlugin() {};
3+
function OptimizeCssAssetsPlugin(options) {
4+
this.options = options || {};
5+
6+
if (this.options.assetNameRegExp === undefined) {
7+
this.options.assetNameRegExp = /\.css$/g;
8+
}
9+
10+
if (this.options.cssProcessor === undefined) {
11+
this.options.cssProcessor = require('cssnano');
12+
}
13+
14+
if (this.options.cssProcessorOptions === undefined) {
15+
this.options.cssProcessorOptions = {};
16+
}
17+
18+
if (this.options.canPrint === undefined) {
19+
this.options.canPrint = true;
20+
}
21+
};
22+
23+
OptimizeCssAssetsPlugin.prototype.print = function() {
24+
if (this.options.canPrint) {
25+
console.log.apply(console, arguments);
26+
}
27+
};
28+
29+
OptimizeCssAssetsPlugin.prototype.processCss = function(css) {
30+
return this.options.cssProcessor.process(css, this.options.cssProcessorOptions);
31+
};
32+
33+
OptimizeCssAssetsPlugin.prototype.createCssAsset = function(css, originalAsset) {
34+
return {
35+
source: function() {
36+
return css;
37+
},
38+
size: function() {
39+
return css.length;
40+
}
41+
};
42+
};
543

644
OptimizeCssAssetsPlugin.prototype.apply = function(compiler) {
45+
46+
var self = this;
47+
748
compiler.plugin('emit', function(compilation, compileCallback) {
849

9-
console.log('');
10-
console.log('Starting to optimize CSS...');
50+
self.print('\nStarting to optimize CSS...');
1151

12-
var cssFiles = _.filter(_.keys(compilation.assets), function(fn){ return fn && fn.match && fn.match(/\.css$/g); });
52+
var assets = compilation.assets;
1353

14-
var counter = 0;
15-
function checkFinish() {
16-
if (cssFiles.length >= counter++) {
17-
console.log('CSS optimize ended.');
18-
compileCallback();
54+
var cssAssetNames = _.filter(
55+
_.keys(assets),
56+
function(assetName) {
57+
return assetName.match(self.options.assetNameRegExp);
1958
}
20-
};
59+
);
60+
61+
var hasErrors = false;
62+
var promises = [];
2163

2264
_.each(
23-
cssFiles,
65+
cssAssetNames,
2466
function(assetName) {
25-
console.log('Processing ' + assetName);
26-
var asset = compilation.assets[assetName];
67+
68+
self.print('Processing ' + assetName + '...');
69+
70+
var asset = assets[assetName];
71+
2772
var originalCss = asset.source();
28-
cssnano.process(originalCss, {discardComments: {removeAll: true}}).then(
73+
74+
var promise = self.processCss(originalCss);
75+
76+
promise.then(
2977
function (result) {
78+
79+
if (hasErrors) {
80+
self.print('Skiping ' + assetName + ' because of an error.');
81+
return;
82+
}
83+
3084
var processedCss = result.css;
31-
compilation.assets[assetName] = {
32-
source: function() {
33-
return processedCss;
34-
},
35-
size: function() {
36-
return processedCss.length;
37-
}
38-
};
39-
console.log('Processing ' + assetName + ' ended, before: ' + originalCss.length + ', after: ' + processedCss.length + ', ratio: ' + (Math.round(((processedCss.length * 100) / originalCss.length) * 100) / 100) + '%');
40-
checkFinish();
85+
86+
assets[assetName] = self.createCssAsset(processedCss, asset);
87+
88+
self.print('Processed ' + assetName + ', before: ' + originalCss.length + ', after: ' + processedCss.length + ', ratio: ' + (Math.round(((processedCss.length * 100) / originalCss.length) * 100) / 100) + '%');
89+
4190
}, function(err) {
42-
console.log('Error processing file: ' + assetName);
43-
console.log(err);
44-
checkFinish();
91+
hasErrors = true;
92+
self.print('Error processing file: ' + assetName);
93+
console.error(err);
4594
}
4695
);
96+
97+
promises.push(promise);
4798
}
4899
);
100+
101+
Promise.all(promises).then(function () { compileCallback(); }, compileCallback);
49102
});
50103
};
51104

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "optimize-css-assets-webpack-plugin",
3-
"version": "1.1.0",
3+
"version": "1.2.0",
44
"author": "Nuno Rodrigues",
55
"description": "A Webpack plugin to optimize \\ minimize CSS assets.",
66
"dependencies": {

0 commit comments

Comments
 (0)