UNPKG

2.26 kBJavaScriptView Raw
1import { createFilter } from 'rollup-pluginutils';
2import { EOL } from 'os';
3import path from 'path';
4import fsp from 'fs-promise';
5import CleanCss from 'clean-css';
6
7var ext = /\.css$/;
8
9var index = function(options) {
10 if ( options === void 0 ) options = {};
11
12 if (!options.include) { options.include = '**/*.css'; }
13
14 var filter = createFilter(options.include, options.exclude);
15 var styles = {};
16 return {
17 name: 'rollup-plugin-css-porter',
18 transform: function transform(code, id) {
19 if (!ext.test(id)) { return }
20 if (!filter(id)) { return }
21
22 // cache all css code
23 if (!styles.hasOwnProperty(id) || styles[id] != code) { styles[id] = code; }
24 return ''
25 },
26 onwrite: function onwrite(opts) {
27 if (!Object.keys(styles).length) { return } // nothing to output
28
29 var outputRaw = options.raw !== false;
30 var outputMinified = options.minified !== false;
31
32 var customRawName = typeof options.raw === 'string';
33 var customMinifiedName = typeof options.minified === 'string';
34
35 // the file of output: use this plugin options.dest or `bundle.write()` options.dest
36 var dest = options.dest || opts.dest;
37 if (!dest && !customRawName && !customMinifiedName) { return } // output nothing if no dest config
38
39 // remove js module extname
40 if (dest) {
41 dest = dest.slice(0, -1 * path.extname(dest).length);
42 }
43
44 // combine all css code
45 var cssCode = [];
46 Object.keys(styles).forEach(function (key) { return cssCode.push(styles[key]); });
47 cssCode = cssCode.join(EOL); // join with platform line break
48
49 var ops = [];
50
51 if (outputRaw) {
52 ops.push(fsp.writeFile(customRawName ? options.raw : dest + '.css', cssCode));
53 }
54
55 if (outputMinified) {
56 ops.push(new Promise(function(resolve, reject) {
57 new CleanCss(options.cleanCSSOptions).minify(cssCode, function (err, m) {
58 if (err) { reject(err); }
59 else { resolve(fsp.writeFile(customMinifiedName ? options.minified : dest + '.min.css', m.styles)); } // output minified css
60 });
61 }));
62 }
63
64 return Promise.all(ops)
65 }
66 }
67};
68
69export default index;