PostCSS Modify Selectors
Post CSS plugin to modify CSS selectors, you can replace, modify or simply add a prefix and suffix. You can match a selector using a simple string compare, a regular expression and even a function.
Installation
$ npm i modify-selectors --save-dev
Usage
const postcss = require("postcss");
postcss([
require("modify-selectors")({
enable: true,
replace: [
{
match: 'body',
with: '.replacedBody',
},
{
match: /wrapper|wrapperContainer/,
with: '.container',
}
],
modify: [],
prefix: [],
modify: [],
})
]).process(cssCode).then((result) => {
console.log(result.css);
});
Match a selector
When your CSS file is processed PostCSS loops all selectors in the file so you can modify them. Please take a looks at the examples below to learn how to check for selectors.
html {
color: red;
}
body {
font-size: 12px;
}
.container {
max-width: 960px;
}
match: '*',
match: 'body',
match: /html|body/,
match: (selector) => {
return selector.includes(':hover');
},
Replace
You can replace selectors completely, for example:
postcss([
require("modify-selectors")({
enable: true,
replace: [
{
match: 'body',
with: '.replacedBody',
},
{
match: 'textarea',
with: 'textarea.small',
}
],
})
]).process(cssCode).then((result) => {
console.log(result.css);
});
Modify
You can modify selectors, for example:
postcss([
require("modify-selectors")({
enable: true,
modify: [
{
match: '*',
with: (selector) => {
return selector.replace('::before', '::after')
},
},
{
match: (selector) => {
return selector.includes(':hover');
},
with: (selector) => {
return selector.replace('::before', '::after')
},
},
],
})
]).process(cssCode).then((result) => {
console.log(result.css);
});
Prefix
postcss([
require("modify-selectors")({
enable: true,
prefix: [
{
match: '*',
with: '.myapp',
},
],
})
]).process(cssCode).then((result) => {
console.log(result.css);
});
Suffix
postcss([
require("modify-selectors")({
enable: true,
suffix: [
{
match: '*',
with: ' > *',
},
],
})
]).process(cssCode).then((result) => {
console.log(result.css);
});