-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathindex.ts
403 lines (353 loc) · 12.6 KB
/
index.ts
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import { dirname } from 'path'
import { createFilter, CreateFilter } from 'rollup-pluginutils'
import type { Plugin } from 'rollup'
export interface CSSPluginOptions {
exclude?: Parameters<CreateFilter>[1]
failOnError?: boolean
/** Literal asset filename, bypasses any hashes in the filename */
fileName?: string
include?: Parameters<CreateFilter>[0]
includePaths?: string[]
insert?: boolean
/** Asset name, defaults to output.css, Rollup may add a hash to this! Check out RollupConfig.output.assetFileNames */
name?: string
/** @deprecated Use `fileName` instead, currently still available for backwards compatibility */
output?: string | false | ((css: string, styles: Styles) => void)
prefix?: string
processor?: (
css: string,
map: string,
styles: Styles
) => CSS | Promise<CSS> | PostCSSProcessor
sass?: SassRenderer
sourceMap?: boolean
verbose?: boolean
watch?: string | string[]
outputStyle?: string
}
type ImporterReturnType = { file: string } | { contents: string } | Error | null
type ImporterDoneCallback = (data: ImporterReturnType) => void
type CSS = string | { css: string; map: string }
interface MappedCSS {
css: string
map: string
}
interface Styles {
[id: string]: string
}
interface PostCSSProcessor {
process: (css: string, options?: any) => MappedCSS
}
interface SassRenderer {
renderSync: (options: SassOptions) => SassResult
}
interface SassOptions {
data: string
}
interface SassResult {
css: Buffer
map?: Buffer
}
export default function scss(options: CSSPluginOptions = {}): Plugin {
const filter = createFilter(
options.include || ['/**/*.css', '/**/*.scss', '/**/*.sass'],
options.exclude
)
const insertStyleFnName = '___$insertStylesToHeader'
const styles: Styles = {}
const fileName =
options.fileName ||
(options.output === 'string' ? options.output : undefined)
const name = options.name || 'output.css'
const prefix = options.prefix ? options.prefix + '\n' : ''
let includePaths = options.includePaths || ['node_modules/']
includePaths.push(process.cwd())
const compileToCSS = async function (scss: string) {
// Compile SASS to CSS
if (scss.length) {
includePaths = includePaths.filter((v, i, a) => a.indexOf(v) === i)
try {
const sass = options.sass || loadSassLibrary()
const render = sass.renderSync(
Object.assign(
{
data: prefix + scss,
outFile: fileName || name,
includePaths,
importer: (
url: string,
prev: string,
done: ImporterDoneCallback
): ImporterReturnType | void => {
/* If a path begins with `.`, then it's a local import and this
* importer cannot handle it. This check covers both `.` and
* `..`.
*
* Additionally, if an import path begins with `url` or `http`,
* then it's a remote import, this importer also cannot handle
* that. */
if (
url.startsWith('.') ||
url.startsWith('url') ||
url.startsWith('http')
) {
/* The importer returns `null` to defer processing the import
* back to the sass compiler. */
return null
}
/* If the requested path begins with a `~`, we remove it. This
* character is used by webpack-contrib's sass-loader to
* indicate the import is from the node_modules folder. Since
* this is so standard in the JS world, the importer supports
* it, by removing it and ignoring it. */
const cleanUrl = url.startsWith('~')
? url.replace('~', '')
: url
/* Now, the importer uses `require.resolve()` to attempt
* to resolve the path to the requested file. In the case
* of a standard node_modules project, this will use Node's
* `require.resolve()`. In the case of a Plug 'n Play project,
* this will use the `require.resolve()` provided by the
* package manager.
*
* This statement is surrounded by a try/catch block because
* if Node or the package manager cannot resolve the requested
* file, they will throw an error, so the importer needs to
* defer to sass, by returning `null`.
*
* The paths property tells `require.resolve()` where to begin
* resolution (i.e. who is requesting the file). */
try {
let resolved = require.resolve(cleanUrl, {
paths: [prefix + scss]
})
const allowedExtensions: string[] = ['.css', '.scss', '.sass'];
const resolvedHasAllowedExtension = allowedExtensions.some((allowedExtension: string) => {
return resolved.endsWith(allowedExtension)
});
/* It is possible that the `resolved` value is unintentionally
* a path to an unintended file which shares the same name
* but has a different file extension. */
if (!resolvedHasAllowedExtension) {
for (const [index, allowedExtension] of allowedExtensions.entries()) {
try {
/* Make an additional attempt to resolve the path by
* specifying the file extension. */
resolved = require.resolve(cleanUrl + allowedExtension, {
paths: [prefix + scss]
})
/* For the first file extension that allows the path to
* be reolved, break out of the loop. */
break
/* If not the path could not be resolved with the
* file extension. */
} catch (e) {
if (index < allowedExtensions.length - 1) {
/* If not the final iteration then proceed
* to the next. */
continue
} else {
/* If the final iteration then re-throw the error
* onto the next catch. */
throw e
}
}
}
}
/* Since `require.resolve()` will throw an error if a file
* doesn't exist. It's safe to assume the file exists and
* pass it off to the sass compiler. */
return { file: resolved }
} catch (e: any) {
/* Just because `require.resolve()` couldn't find the file
* doesn't mean it doesn't exist. It may still be a local
* import that just doesn't list a relative path, so defer
* processing back to sass by returning `null` */
return null
}
}
},
options
)
)
const css = render.css.toString()
const map = render.map ? render.map.toString() : ''
// Possibly process CSS (e.g. by PostCSS)
if (typeof options.processor === 'function') {
const result = await options.processor(css, map, styles)
// TODO: figure out how to check for
// @ts-ignore
const postcss: PostCSSProcessor = result
// PostCSS support
if (typeof postcss.process === 'function') {
return Promise.resolve(
postcss.process(css, {
from: undefined,
to: fileName || name,
map: map ? { prev: map, inline: false } : null
})
)
}
// @ts-ignore
const output: string | MappedCSS = result
return stringToCSS(output)
}
return { css, map }
} catch (e: any) {
if (options.failOnError) {
throw e
}
console.log()
console.log(red('Error:\n\t' + e.message))
if (e.message.includes('Invalid CSS')) {
console.log(green('Solution:\n\t' + 'fix your Sass code'))
console.log('Line: ' + e.line)
console.log('Column: ' + e.column)
}
if (e.message.includes('sass') && e.message.includes('find module')) {
console.log(green('Solution:\n\t' + 'npm install --save-dev sass'))
}
if (e.message.includes('node-sass') && e.message.includes('bindings')) {
console.log(green('Solution:\n\t' + 'npm rebuild node-sass --force'))
}
console.log()
}
}
return { css: '', map: '' }
}
return {
name: 'scss',
intro() {
return options.insert === true
? insertStyleFn.replace(/insertStyleFn/, insertStyleFnName)
: ''
},
async transform(code, id) {
if (!filter(id)) {
return
}
// Add the include path before doing any processing
includePaths.push(dirname(id))
// Rebuild all scss files if anything happens to this folder
// TODO: check if it's possible to get a list of all dependent scss files
// and only watch those
if (options.watch) {
const files = Array.isArray(options.watch)
? options.watch
: [options.watch]
files.forEach(file => this.addWatchFile(file))
}
if (options.insert === true) {
// When the 'insert' is enabled, the stylesheet will be inserted into <head/> tag.
const { css, map } = await compileToCSS(code)
return {
code:
'export default ' +
insertStyleFnName +
'(' +
JSON.stringify(css) +
')',
map: { mappings: '' }
}
} else if (options.output === false) {
// When output is disabled, the stylesheet is exported as a string
const { css, map } = await compileToCSS(code)
return {
code: 'export default ' + JSON.stringify(css),
map: { mappings: '' }
}
}
// Map of every stylesheet
styles[id] = code
return ''
},
async generateBundle(opts) {
// No stylesheet needed
if (options.output === false || options.insert === true) {
return
}
// Combine all stylesheets
let scss = ''
for (const id in styles) {
scss += styles[id] || ''
}
const compiled = await compileToCSS(scss)
if (typeof compiled !== 'object' || typeof compiled.css !== 'string') {
return
}
// Emit styles through callback
if (typeof options.output === 'function') {
options.output(compiled.css, styles)
return
}
// Don't create unwanted empty stylesheets
if (!compiled.css.length) {
return
}
// Emit styles to file
this.emitFile({
type: 'asset',
source: compiled.css,
name,
fileName
})
if (options.sourceMap && compiled.map) {
let sourcemap = compiled.map
if (typeof compiled.map.toString === 'function') {
sourcemap = compiled.map.toString()
}
this.emitFile({
type: 'asset',
source: sourcemap,
name: name && name + '.map',
fileName: fileName && fileName + '.map'
})
}
}
}
}
/**
* Create a style tag and append to head tag
*
* @param {String} css style
* @return {String} css style
*/
const insertStyleFn = `function insertStyleFn(css) {
if (!css) {
return
}
if (typeof window === 'undefined') {
return
}
const style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.innerHTML = css;
document.head.appendChild(style);
return css
}`
function loadSassLibrary(): SassRenderer {
try {
return require('sass')
} catch (e) {
return require('node-sass')
}
}
function stringToCSS(input: string | CSS): MappedCSS {
if (typeof input === 'string') {
return { css: input, map: '' }
}
return input
}
function red(text: string) {
return '\x1b[1m\x1b[31m' + text + '\x1b[0m'
}
function green(text: string) {
return '\x1b[1m\x1b[32m' + text + '\x1b[0m'
}
function getSize(bytes: number) {
return bytes < 10000
? bytes.toFixed(0) + ' B'
: bytes < 1024000
? (bytes / 1024).toPrecision(3) + ' kB'
: (bytes / 1024 / 1024).toPrecision(4) + ' MB'
}