forked from thgh/rollup-plugin-scss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.es.js
119 lines (102 loc) · 2.82 KB
/
index.es.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { existsSync, mkdirSync, writeFile } from 'fs'
import { dirname } from 'path'
import { createFilter } from 'rollup-pluginutils'
import { renderSync } from 'node-sass'
export default function css(options = {}) {
const filter = createFilter(options.include || ['**/*.css', '**/*.scss', '**/*.sass'], options.exclude);
let dest = options.output
const styles = {}
let includePaths = options.includePaths || []
includePaths.push(process.cwd())
return {
name: 'css',
transform(code, id) {
if (!filter(id)) {
return
}
// When output is disabled, the stylesheet is exported as a string
if (options.output === false) {
return {
code: 'export default ' + JSON.stringify(code),
map: { mappings: '' }
}
}
// Map of every stylesheet
styles[id] = code
includePaths.push(dirname(id))
return ''
},
ongenerate (opts) {
// No stylesheet needed
if (options.output === false) {
return
}
// Combine all stylesheets
let css = ''
for (const id in styles) {
css += styles[id] || ''
}
// Compile SASS to CSS
includePaths = includePaths.filter((v, i, a) => a.indexOf(v) === i)
css = renderSync(Object.assign({
data: css,
includePaths
}, options)).css.toString();
// Emit styles through callback
if (typeof options.output === 'function') {
options.output(css, styles)
return
}
if (typeof dest !== 'string') {
// Don't create unwanted empty stylesheets
if (!css.length) {
return
}
// Guess destination filename
dest = opts.dest || 'bundle.js'
if (dest.endsWith('.js')) {
dest = dest.slice(0, -3)
}
dest = dest + '.css'
}
// Ensure that dest parent folders exist (create the missing ones)
ensureParentDirsSync(dirname(dest))
// Emit styles to file
return new Promise(function (resolve, reject) {
writeFile(dest, css, (err) => {
if (err) {
reject(err)
} else {
if (opts.verbose !== false) {
console.log(green(dest), getSize(css.length))
}
resolve()
}
})
})
}
}
}
function green (text) {
return '\u001b[1m\u001b[32m' + text + '\u001b[39m\u001b[22m'
}
function getSize (bytes) {
return bytes < 10000
? bytes.toFixed(0) + ' B'
: bytes < 1024000
? (bytes / 1024).toPrecision(3) + ' kB'
: (bytes / 1024 / 1024).toPrecision(4) + ' MB'
}
function ensureParentDirsSync (dir) {
if (existsSync(dir)) {
return
}
try {
mkdirSync(dir)
} catch (err) {
if (err.code === 'ENOENT') {
ensureParentDirsSync(dirname(dir))
ensureParentDirsSync(dir)
}
}
}