-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
239 lines (190 loc) · 8.92 KB
/
index.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import fs from 'fs'
import path from 'path'
import resolve from 'resolve'
import styleInject from 'style-inject'
import sass from 'node-sass'
import { createFilter } from 'rollup-pluginutils'
import mkdirp from 'mkdirp';
const START_COMMENT_FLAG = '/* collect-postcss-start'
const END_COMMENT_FLAG = 'collect-postcss-end */'
const ESCAPED_END_COMMENT_FLAG = 'collect-postcss-escaped-end * /'
const ESCAPED_END_COMMENT_REGEX = /collect-postcss-escaped-end \* \//g
const escapeRegex = str => str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
const findRegex = new RegExp(`${escapeRegex(START_COMMENT_FLAG)}([^]*?)${escapeRegex(END_COMMENT_FLAG)}`, 'g')
const replaceRegex = new RegExp(`${escapeRegex(START_COMMENT_FLAG)}[^]*?${escapeRegex(END_COMMENT_FLAG)}`)
const importRegex = new RegExp('@import([^;]*);', 'g')
const importExtensions = ['.scss', '.sass']
const injectFnName = '__$styleInject'
const injectStyleFuncCode = styleInject
.toString()
.replace(/styleInject/, injectFnName)
export default (options = {}) => {
const extensions = options.extensions || importExtensions
const filter = createFilter(options.include || ['**/*.scss', '**/*.sass'], options.exclude)
const extract = Boolean(options.extract)
const extractFn = typeof options.extract === 'function' ? options.extract : null
const extractPath = typeof options.extract === 'string' ? options.extract : null
const importOnce = Boolean(options.importOnce)
let cssExtract = ''
let visitedImports = new Set()
return {
name: 'collect-sass',
intro () {
if (extract) {
return null
}
return injectStyleFuncCode
},
transform (code, id) {
if (!filter(id)) { return null }
if (extensions.indexOf(path.extname(id)) === -1) { return null }
const relBase = path.dirname(id)
const fileImports = new Set([id])
visitedImports.add(id)
// Resolve imports before lossing relative file info
// Find all import statements to replace
let transformed = code.replace(importRegex, (match, p1) => {
const paths = p1.split(/[,]/).map(p => {
const orgName = p.trim() // strip whitespace
let name = orgName
if (name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
name = name.substring(1, name.length - 1) // string quotes
}
// Exclude CSS @import: http://sass-lang.com/documentation/file.SASS_REFERENCE.html#import
if (path.extname(name) === '.css') { return orgName }
if (name.startsWith('http://')) { return orgName }
if (name.startsWith('url(')) { return orgName }
const fileName = path.basename(name)
const dirName = path.dirname(name)
// libsass's file name resolution: https://github.com/sass/node-sass/blob/1b9970a/src/libsass/src/file.cpp#L300
if (fs.existsSync(path.join(relBase, dirName, fileName))) {
const absPath = path.join(relBase, name)
if (importOnce && visitedImports.has(absPath)) {
return null
}
visitedImports.add(absPath)
fileImports.add(absPath)
return JSON.stringify(absPath)
}
if (fs.existsSync(path.join(relBase, dirName, `_${fileName}`))) {
const absPath = path.join(relBase, `_${name}`)
if (importOnce && visitedImports.has(absPath)) {
return null
}
visitedImports.add(absPath)
fileImports.add(absPath)
return JSON.stringify(absPath)
}
for (let i = 0; i < importExtensions.length; i += 1) {
const absPath = path.join(relBase, dirName, `_${fileName}${importExtensions[i]}`)
if (fs.existsSync(absPath)) {
if (importOnce && visitedImports.has(absPath)) {
return null
}
visitedImports.add(absPath)
fileImports.add(absPath)
return JSON.stringify(absPath)
}
}
for (let i = 0; i < importExtensions.length; i += 1) {
const absPath = path.join(relBase, `${name}${importExtensions[i]}`)
if (fs.existsSync(absPath)) {
if (importOnce && visitedImports.has(absPath)) {
return null
}
visitedImports.add(absPath)
fileImports.add(absPath)
return JSON.stringify(absPath)
}
}
let nodeResolve
try {
nodeResolve = resolve.sync(path.join(dirName, `_${fileName}`), { extensions })
} catch (e) {} // eslint-disable-line no-empty
try {
nodeResolve = resolve.sync(path.join(dirName, fileName), { extensions })
} catch (e) {} // eslint-disable-line no-empty
if (nodeResolve) {
if (importOnce && visitedImports.has(nodeResolve)) {
return null
}
visitedImports.add(nodeResolve)
fileImports.add(nodeResolve)
return JSON.stringify(nodeResolve)
}
this.warn(`Unresolved path in ${id}: ${name}`)
return orgName
})
const uniquePaths = paths.filter(p => p !== null)
if (uniquePaths.length) {
return `@import ${uniquePaths.join(', ')};`
}
return ''
})
// Escape */ end comments
transformed = transformed.replace(/\*\//g, ESCAPED_END_COMMENT_FLAG)
// Add sass imports to bundle as JS comment blocks
return {
code: START_COMMENT_FLAG + transformed + END_COMMENT_FLAG,
map: { mappings: '' },
dependencies: Array.from(fileImports),
}
},
transformBundle (source) {
// Reset paths
visitedImports = new Set()
// Extract each sass file from comment blocks
let accum = ''
let match = findRegex.exec(source)
while (match !== null) {
accum += match[1]
match = findRegex.exec(source)
}
if (accum) {
// Add */ end comments back
accum = accum.replace(ESCAPED_END_COMMENT_REGEX, '*/')
// Transform sass
const css = sass.renderSync({
data: accum,
includePaths: ['node_modules'],
}).css.toString()
if (!extract) {
const injected = `${injectFnName}(${JSON.stringify(css)});`
// Replace first instance with output. Remove all other instances
return {
code: source.replace(replaceRegex, injected).replace(findRegex, ''),
map: { mappings: '' },
}
}
// Store css for writing
cssExtract = css
}
// Remove all other instances
return {
code: source.replace(findRegex, ''),
map: { mappings: '' },
}
},
onwrite (opts) {
if (extract && cssExtract) {
if (extractFn) return extractFn(cssExtract, opts)
const destPath = extractPath ||
path.join(path.dirname(opts.dest), `${path.basename(opts.dest, path.extname(opts.dest))}.css`)
return new Promise((resolveDir, rejectDir) => {
mkdirp(path.dirname(destPath), err => {
if (err) { rejectDir(err) }
else resolveDir()
});
}).then(() => {
return new Promise((resolveExtract, rejectExtract) => {
fs.writeFile(destPath, cssExtract, err => {
if (err) { rejectExtract(err) }
resolveExtract()
})
})
})
}
return null
},
}
}