Prefix every CSS selector with a custom namespace
.a => .prefix
$ npm install postcss-prefix-x
const prefixer = require('postcss-prefix-x')
// css to be processed
const css = fs.readFileSync("input.css", "utf8")
const out = postcss().use(prefixer({
prefix: '.some-selector',
})).process(css).css
Using the options above and the CSS below...
.c {
color: coral;
}
You will get the following output
.some-selector {
color: coral;
}
Use it like you'd use any other PostCSS plugin. If you also have autoprefixer
in your webpack config then make sure that postcss-prefix-x
is called first. This is needed to avoid running the prefixer twice on both standard selectors and vendor specific ones (ex: @keyframes
and @webkit-keyframes
).
module: {
rules: [{
test: /\.css$/,
use: [
require.resolve('style-loader'),
require.resolve('css-loader'),
{
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
plugins: {
"postcss-prefix-x": {
prefix: '.some-prefix',
},
autoprefixer: {
browsers: ['last 4 versions']
}
}
}
}
}
]
}]
}
Following the same way of Webpack but for Vite:
import prefixer from 'postcss-prefix-x';
import autoprefixer from 'autoprefixer';
...
export default defineConfig({
...
css: {
postcss: {
plugins: [
prefixer({
prefix: '.some-prefix',
}),
autoprefixer({}) // add options if needed
],
}
},
...
});
Name | Type | Description |
---|---|---|
prefix |
string |
This string is added before every CSS selector |