Skip to content

Commit c3f021a

Browse files
committed
Prefix all classes in a selector, don't assume single class
1 parent d1423ba commit c3f021a

File tree

4 files changed

+47
-2
lines changed

4 files changed

+47
-2
lines changed

__tests__/prefixTree.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ test('it handles a function as the prefix', () => {
2929
`
3030

3131
const prefixFunc = selector => {
32+
return selector === '.foo' ? 'tw-' : ''
3233
if (selector === '.foo') {
3334
return 'tw-'
3435
}
@@ -40,3 +41,17 @@ test('it handles a function as the prefix', () => {
4041
expect(result.css).toEqual(expected)
4142
expect(result.warnings().length).toBe(0)
4243
})
44+
45+
test('it prefixes all classes in a selector', () => {
46+
const input = postcss.parse(`
47+
.btn-blue .w-1\\/4 > h1.text-xl + a .bar { color: red; }
48+
`)
49+
50+
const expected = `
51+
.tw-btn-blue .tw-w-1\\/4 > h1.tw-text-xl + a .tw-bar { color: red; }
52+
`
53+
54+
const result = prefixTree(input, 'tw-').toResult()
55+
expect(result.css).toEqual(expected)
56+
expect(result.warnings().length).toBe(0)
57+
})

__tests__/processPlugins.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,3 +755,26 @@ test('variants can still be specified when ignoring prefix and important options
755755
}
756756
`)
757757
})
758+
759+
test('prefix will prefix all classes in a selector', () => {
760+
const [components] = processPluginsWithValidConfig({
761+
plugins: [
762+
function({ addComponents, prefix }) {
763+
addComponents({
764+
[prefix('.btn-blue .w-1\\/4 > h1.text-xl + a .bar')]: {
765+
backgroundColor: 'blue',
766+
},
767+
})
768+
},
769+
],
770+
options: {
771+
prefix: 'tw-',
772+
},
773+
})
774+
775+
expect(css(components)).toMatchCss(`
776+
.tw-btn-blue .tw-w-1\\/4 > h1.tw-text-xl + a .tw-bar {
777+
background-color: blue
778+
}
779+
`)
780+
})

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@
5050
"postcss": "^6.0.9",
5151
"postcss-functions": "^3.0.0",
5252
"postcss-js": "^1.0.1",
53-
"postcss-nested": "^3.0.0"
53+
"postcss-nested": "^3.0.0",
54+
"postcss-selector-parser": "^3.1.1"
5455
},
5556
"browserslist": [
5657
"> 1%"

src/util/prefixSelector.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1+
import parser from 'postcss-selector-parser'
2+
13
export default function(prefix, selector) {
24
const getPrefix = typeof prefix === 'function' ? prefix : () => prefix
35

4-
return `.${getPrefix(selector)}${selector.slice(1)}`
6+
return parser(selectors => {
7+
selectors.walkClasses((classSelector) => {
8+
classSelector.value = `${getPrefix('.' + classSelector.value)}${classSelector.value}`
9+
})
10+
}).processSync(selector)
511
}

0 commit comments

Comments
 (0)