feat(compiler-sfc): built-in support for css modules
This commit is contained in:
@@ -25,6 +25,20 @@ export interface SFCStyleCompileOptions {
|
||||
|
||||
export interface SFCAsyncStyleCompileOptions extends SFCStyleCompileOptions {
|
||||
isAsync?: boolean
|
||||
// css modules support, note this requires async so that we can get the
|
||||
// resulting json
|
||||
modules?: boolean
|
||||
// maps to postcss-modules options
|
||||
// https://github.com/css-modules/postcss-modules
|
||||
modulesOptions?: {
|
||||
scopeBehaviour?: 'global' | 'local'
|
||||
globalModulePaths?: string[]
|
||||
generateScopedName?:
|
||||
| string
|
||||
| ((name: string, filename: string, css: string) => string)
|
||||
hashPrefix?: string
|
||||
localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly'
|
||||
}
|
||||
}
|
||||
|
||||
export interface SFCStyleCompileResults {
|
||||
@@ -32,6 +46,7 @@ export interface SFCStyleCompileResults {
|
||||
map: RawSourceMap | undefined
|
||||
rawResult: LazyResult | Result | undefined
|
||||
errors: Error[]
|
||||
modules?: Record<string, string>
|
||||
}
|
||||
|
||||
export function compileStyle(
|
||||
@@ -44,7 +59,7 @@ export function compileStyle(
|
||||
}
|
||||
|
||||
export function compileStyleAsync(
|
||||
options: SFCStyleCompileOptions
|
||||
options: SFCAsyncStyleCompileOptions
|
||||
): Promise<SFCStyleCompileResults> {
|
||||
return doCompileStyle({ ...options, isAsync: true }) as Promise<
|
||||
SFCStyleCompileResults
|
||||
@@ -57,8 +72,10 @@ export function doCompileStyle(
|
||||
const {
|
||||
filename,
|
||||
id,
|
||||
scoped = true,
|
||||
scoped = false,
|
||||
trim = true,
|
||||
modules = false,
|
||||
modulesOptions = {},
|
||||
preprocessLang,
|
||||
postcssOptions,
|
||||
postcssPlugins
|
||||
@@ -75,6 +92,23 @@ export function doCompileStyle(
|
||||
if (scoped) {
|
||||
plugins.push(scopedPlugin(id))
|
||||
}
|
||||
let cssModules: Record<string, string> | undefined
|
||||
if (modules) {
|
||||
if (options.isAsync) {
|
||||
plugins.push(
|
||||
require('postcss-modules')({
|
||||
...modulesOptions,
|
||||
getJSON: (cssFileName: string, json: Record<string, string>) => {
|
||||
cssModules = json
|
||||
}
|
||||
})
|
||||
)
|
||||
} else {
|
||||
throw new Error(
|
||||
'`modules` option can only be used with compileStyleAsync().'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const postCSSOptions: ProcessOptions = {
|
||||
...postcssOptions,
|
||||
@@ -108,6 +142,7 @@ export function doCompileStyle(
|
||||
code: result.css || '',
|
||||
map: result.map && (result.map.toJSON() as any),
|
||||
errors,
|
||||
modules: cssModules,
|
||||
rawResult: result
|
||||
}))
|
||||
.catch(error => ({
|
||||
|
||||
Reference in New Issue
Block a user