/
style.ts
66 lines (62 loc) · 1.84 KB
/
style.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
import type { SFCDescriptor } from 'vue/compiler-sfc'
import type { ExistingRawSourceMap, TransformPluginContext } from 'rollup'
import type { RawSourceMap } from 'source-map'
import { formatPostcssSourceMap } from 'vite'
import type { ResolvedOptions } from '.'
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export async function transformStyle(
code: string,
descriptor: SFCDescriptor,
index: number,
options: ResolvedOptions,
pluginContext: TransformPluginContext,
filename: string
) {
const block = descriptor.styles[index]
// vite already handles pre-processors and CSS module so this is only
// applying SFC-specific transforms like scoped mode and CSS vars rewrite (v-bind(var))
const result = await options.compiler.compileStyleAsync({
...options.style,
filename: descriptor.filename,
id: `data-v-${descriptor.id}`,
isProd: options.isProduction,
source: code,
scoped: block.scoped,
...(options.cssDevSourcemap
? {
postcssOptions: {
map: {
from: filename,
inline: false,
annotation: false
}
}
}
: {})
})
if (result.errors.length) {
result.errors.forEach((error: any) => {
if (error.line && error.column) {
error.loc = {
file: descriptor.filename,
line: error.line + block.loc.start.line,
column: error.column
}
}
pluginContext.error(error)
})
return null
}
const map = result.map
? await formatPostcssSourceMap(
// version property of result.map is declared as string
// but actually it is a number
result.map as Omit<RawSourceMap, 'version'> as ExistingRawSourceMap,
filename
)
: ({ mappings: '' } as any)
return {
code: result.code,
map: map
}
}