UNPKG

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