Kawd
Kawd

Reputation: 4450

How do I parse CSS to prefix CSS selectors

I have the following my-file.css:

.a [data-smth] { ... }
.b .c.d { ... }
.e { ... }
#f { ... }

and I want to do something like the following (pseudocode) in Node.js:

let css = readFile('my-file.css')
let prefixedCss = prefixClasses(css, 'prfx-')
writeFile(prefixedCss, 'my-prefixed-file.css')

to end up with my-prefixed-file.css:

.prfx-a [data-smth] { ... }
.prfx-b .prfx-c.prfx-d { ... }
.prfx-e { ... }
#f { ... }

I have found these npm modules:

https://github.com/vic/prefix-css (hasn't been updated in years and has issues)
https://pegjs.org/ (requires lots of low-level AST configuration)

But I was wondering whether there are better/safer solutions that have already been tested/become standard practice ?

NOTE: The above file contents was just an example. I'm looking for a way to achieve this for files whose content is completely unknown to me. So I'm looking for a "universal" solution.

Any help would be most welcome & thank you in advance! :-)

Upvotes: 1

Views: 2531

Answers (1)

connexo
connexo

Reputation: 56754

You might want to check https://github.com/marceloucker/postcss-prefixer#postcss-prefixer.

postcss-prefixer

Build Status dependencies Status devDependencies Status License: MIT

PostCSS plugin to add a prefix to all css selectors classes and ids.

Usage

With PostCSS cli:

Install postcss-cli and postcss-prefixer on your project directory:

npm install postcss-cli postcss-prefixer --save-dev

and at your package.json

"scripts": {
      "postcss": "postcss input.css -u postcss-prefixer -o output.css"
}

Others

postcss([ require('postcss-prefixer')({ /* options */ }) ])

Options

prefix

Type: `string`<br>
Default: none

String to be used as prefix

ignore

Type: `array`<br>
Default: `[]`

Array of selectors to be ignored by the plugin, accepts string and regex.

Example

Example of usage with results generated by the plugin.

Code

const postcss = require('postcss');
const prefixer = require('postcss-prefixer');
const input = fs.readFileSync('path/to/file.css',  'utf-8');
const output = postcss([
  prefixer({
        prefix: 'prefix-'
        ignore: [ /selector-/, '.ignore', '#ignore' ]
    })
]).process(input);

Input:

#selector-one .example {
  /* content */
}
.selector-two .example2 {
  /* content */
}
#ignore .ignore {
  /* content */
}
#ignore .other {
  /* content */
}

Output:

#selector-one .prefix-example {
  /* content */
}
.selector-two .prefix-example2 {
  /* content */
}
#ignore .ignore {
  /* content */
}
#ignore .prefix-other {
  /* content */
}

Credits

Plugin based on postcss-class-prefix create by thompsongl.

Upvotes: 2

Related Questions