1 | import { createFilter } from 'rollup-pluginutils'
|
2 | import { EOL } from 'os'
|
3 | import path from 'path'
|
4 | import fsp from 'fs-promise'
|
5 | import CleanCss from 'clean-css'
|
6 |
|
7 | const ext = /\.css$/;
|
8 |
|
9 | export 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 |
|
21 | if (!styles.hasOwnProperty(id) || styles[id] != code) styles[id] = code
|
22 | return ''
|
23 | },
|
24 | onwrite(opts) {
|
25 | if (!Object.keys(styles).length) return
|
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 |
|
34 | let dest = options.dest || opts.dest
|
35 | if (!dest && !customRawName && !customMinifiedName) return
|
36 |
|
37 |
|
38 | if (dest) {
|
39 | dest = dest.slice(0, -1 * path.extname(dest).length)
|
40 | }
|
41 |
|
42 |
|
43 | let cssCode = []
|
44 | Object.keys(styles).forEach(key => cssCode.push(styles[key]))
|
45 | cssCode = cssCode.join(EOL)
|
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))
|
58 | })
|
59 | }))
|
60 | }
|
61 |
|
62 | return Promise.all(ops)
|
63 | }
|
64 | }
|
65 | }
|