feat: allow inline postcss config

close #1061
This commit is contained in:
Evan You 2021-01-20 16:44:31 -05:00
parent 0c0e2af359
commit 6bd21402a9
2 changed files with 33 additions and 5 deletions

View File

@ -128,6 +128,14 @@ export default ({ command, mode }) => {
Configure CSS modules behavior. The options are passed on to [postcss-modules](https://github.com/css-modules/postcss-modules).
### css.postcss
- **Type:** `string | (postcss.ProcessOptions & { plugins?: postcss.Plugin[] })`
Inline PostCSS config (expects the same format as `postcss.config.js`), or a custom path to search PostCSS config from (default is project root). The search is done using [postcss-load-config](https://github.com/postcss/postcss-load-config).
Note if an inline config is provided, Vite will not search for other PostCSS config sources.
### css.preprocessorOptions
- **Type:** `Record<string, object>`

View File

@ -4,7 +4,8 @@ import {
asyncReplace,
cleanUrl,
generateCodeFrame,
isDataUrl
isDataUrl,
isObject
} from '../utils'
import path from 'path'
import { Plugin } from '../plugin'
@ -33,6 +34,11 @@ export interface CSSOptions {
*/
modules?: CSSModulesOptions | false
preprocessorOptions?: Record<string, any>
postcss?:
| string
| (ProcessOptions & {
plugins?: PostcssPlugin[]
})
}
export interface CSSModulesOptions {
@ -311,7 +317,7 @@ async function compileCSS(
// although at serve time it can work without processing, we do need to
// crawl them in order to register watch dependencies.
const needInlineImport = code.includes('@import')
const postcssConfig = await loadPostcssConfig(config.root)
const postcssConfig = await resolvePostcssConfig(config)
const lang = id.match(cssLangRE)?.[1]
// 1. plain css that needs no processing
@ -437,14 +443,28 @@ interface PostCSSConfigResult {
let cachedPostcssConfig: PostCSSConfigResult | null | undefined
async function loadPostcssConfig(
root: string
async function resolvePostcssConfig(
config: ResolvedConfig
): Promise<PostCSSConfigResult | null> {
if (cachedPostcssConfig !== undefined) {
return cachedPostcssConfig
}
// inline postcss config via vite config
const inlineOptions = config.css?.postcss
if (isObject(inlineOptions)) {
const result = {
options: { ...inlineOptions },
plugins: inlineOptions.plugins || []
}
delete result.options.plugins
return (cachedPostcssConfig = result)
}
try {
return (cachedPostcssConfig = await postcssrc({}, root))
const searchPath =
typeof inlineOptions === 'string' ? inlineOptions : config.root
return (cachedPostcssConfig = await postcssrc({}, searchPath))
} catch (e) {
if (!/No PostCSS Config found/.test(e.message)) {
throw e