Skip to content

Commit

Permalink
feat: add option to keep class names for css modules
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Aug 5, 2022
1 parent 135b6d8 commit 4743748
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
5 changes: 4 additions & 1 deletion packages/vitest/src/node/config.ts
Expand Up @@ -185,8 +185,11 @@ export function resolveConfig(
resolved.passWithNoTests ??= true

resolved.css ??= {}
if (typeof resolved.css === 'object')
if (typeof resolved.css === 'object') {
resolved.css.include ??= [/\.module\./]
resolved.css.modules ??= {}
resolved.css.modules.mangleClassName ??= false
}

resolved.cache ??= { dir: '' }
if (resolved.cache)
Expand Down
26 changes: 25 additions & 1 deletion packages/vitest/src/node/plugins/cssEnabler.ts
Expand Up @@ -4,11 +4,16 @@ import type { Vitest } from '../core'

const cssLangs = '\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)'
const cssLangRE = new RegExp(cssLangs)
const cssModuleRE = new RegExp(`\\.module${cssLangs}`)

const isCSS = (id: string) => {
return cssLangRE.test(id)
}

const isCSSModule = (id: string) => {
return cssModuleRE.test(id)
}

export function CSSEnablerPlugin(ctx: Vitest): VitePlugin {
const shouldProcessCSS = (id: string) => {
const { css } = ctx.config
Expand All @@ -21,14 +26,33 @@ export function CSSEnablerPlugin(ctx: Vitest): VitePlugin {
return false
}

const shouldReturnProxy = (id: string) => {
const { css } = ctx.config
if (typeof css === 'boolean')
return css
if (!isCSSModule(id))
return false
return !css.modules?.mangleClassName
}

return {
name: 'vitest:css-enabler',
enforce: 'pre',
transform(code, id) {
if (!isCSS(id))
return
if (!shouldProcessCSS(id))
if (!shouldProcessCSS(id)) {
return { code: '' }
}
else if (shouldReturnProxy(id)) {
// TODO parse and check if object actually exists
const code = `export default new Proxy(Object.create(null), {
get(_, style) {
return style;
},
})`
return { code }
}
},
}
}
5 changes: 4 additions & 1 deletion packages/vitest/src/types/config.ts
Expand Up @@ -370,11 +370,14 @@ export interface InlineConfig {
*
* When excluded, the CSS files will be replaced with empty strings to bypass the subsequent processing.
*
* @default { include: [/\.module\./] }
* @default { include: [/\.module\./], modules: { mangleClassName: false } }
*/
css?: boolean | {
include?: RegExp | RegExp[]
exclude?: RegExp | RegExp[]
modules?: {
mangleClassName?: boolean
}
}
/**
* A number of tests that are allowed to run at the same time marked with `test.concurrent`.
Expand Down

0 comments on commit 4743748

Please sign in to comment.