Skip to content

Commit

Permalink
feat(transformer-compile-class): add alwaysHash option, workaround #…
Browse files Browse the repository at this point in the history
…2366 (#3173)

Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
evanryuu and antfu committed Dec 2, 2023
1 parent ef98105 commit 08e2397
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
12 changes: 11 additions & 1 deletion packages/transformer-compile-class/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ export interface CompileClassOptions {
*/
hashFn?: (str: string) => string

/**
* Allow add hash to class name even if the class name is explicitly defined
*
* @default false
*/
alwaysHash?: boolean

/**
* Left unknown classes inside the string
*
Expand All @@ -63,6 +70,7 @@ export default function transformerCompileClass(options: CompileClassOptions = {
classPrefix = 'uno-',
hashFn = hash,
keepUnknown = true,
alwaysHash = false,
} = options
// #2866
const compiledClass = new Set()
Expand Down Expand Up @@ -105,6 +113,8 @@ export default function transformerCompileClass(options: CompileClassOptions = {

if (match.groups && match.groups.name) {
hash = match.groups.name
if (alwaysHash)
hash += `-${hashFn(body)}`
explicitName = true
}
else {
Expand All @@ -115,7 +125,7 @@ export default function transformerCompileClass(options: CompileClassOptions = {
if (tokens && tokens.has(className) && explicitName) {
const existing = uno.config.shortcuts.find(i => i[0] === className)
if (existing && existing[1] !== body)
throw new Error(`Duplicated compile class name "${className}". One is "${body}" and the other is "${existing[1]}" Please choose different class name`)
throw new Error(`Duplicated compile class name "${className}". One is "${body}" and the other is "${existing[1]}". Please choose different class name or set 'alwaysHash' to 'true'.`)
}

compiledClass.add(className)
Expand Down
4 changes: 2 additions & 2 deletions test/transformer-compile-class.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,10 @@ describe('transformer-compile-class', () => {
<div class=":uno-foo: w-2"/>
`.trim())
}).rejects
.toMatchInlineSnapshot('[Error: Duplicated compile class name "uno-foo". One is "w-2" and the other is "w-1" Please choose different class name]')
.toMatchInlineSnapshot(`[Error: Duplicated compile class name "uno-foo". One is "w-2" and the other is "w-1". Please choose different class name or set 'alwaysHash' to 'true'.]`)
})

it('custom class name should not conflicts when the content is the same', async () => {
it('custom class name should not conflict when the content is the same', async () => {
const result = await transform(`
<div class=":uno-foo: h-1 w-1"/>
<div class=":uno-foo: w-1 h-1"/>
Expand Down

0 comments on commit 08e2397

Please sign in to comment.