继续compileSFC方法:
// varlet-cli/src/compiler/compileSFC.ts
import { compileStyle } from '@vue/compiler-sfc'
export async function compileSFC(sfc: string) {
// ...
if (script) {
// ...
// script
// 编译js
await compileScript(content, sfc)
// style
// 编译样式
for (let index = 0; index < styles.length; index++) {
const style: SFCStyleBlock = styles[index]
// replaceExt方法接收文件名称,比如xxx.vue,然后使用第二个参数替换文件名称的扩展名,比如处理完会返回xxxSfc.less
const file = replaceExt(sfc, `Sfc${index || ''}.${style.lang || 'css'}`)
// 编译样式块
let { code } = compileStyle({
source: style.content,
filename: file,
id: scopeId,
scoped: style.scoped,
})
// 去除样式中的导入语句
code = extractStyleDependencies(file, code, STYLE_IMPORT_RE, style.lang as 'css' | 'less', true)
// 将解析后的样式写入文件
writeFileSync(file, clearEmptyLine(code), 'utf-8')
// 如果样式块是less语言,那么同时也编译成css文件
style.lang === 'less' && (await compileLess(file))
}
}
}
调用了compileScript方法编译script内容,这个方法我们下一小节再说。然后遍历style块,每个块都会生成相应的样式文件,比如Button.vue组件存在一个less语言的style块

那么会生成一个ButtonSfc.less,因为是less,所以同时也会再编译生成一个ButtonSfc.css文件,当然这两个样式文件里只包括内联在Vue单文件中的样式,不包括使用@import导入的样式,所以生成的这两个样式文件都是空的:

编译样式块使用的是@vue/compiler-sfc的compileStyle方法,它会帮我们处理