首页 > 解决方案 > 如何解析 CSS 以添加 CSS 选择器前缀

问题描述

我有以下内容my-file.css

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

我想在 Node.js 中执行以下操作(伪代码):

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

最终得到my-prefixed-file.css

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

我找到了这些 npm 模块:

https://github.com/vic/prefix-css(多年未更新且存在问题)
https://pegjs.org/(需要大量低级 AST 配置)

但我想知道是否有更好/更安全的解决方案已经过测试/成为标准做法?

注意: 以上文件内容只是一个示例。我正在寻找一种方法来实现我完全不知道其内容的文件。所以我正在寻找一个“通用”的解决方案。

任何帮助都将受到欢迎,并在此先感谢您!:-)

标签: cssnode.jsparsing

解决方案


您可能需要检查https://github.com/marceloucker/postcss-prefixer#postcss-prefixer

postcss 前缀

构建状态 依赖状态 devDependencies 状态 执照:麻省理工学院

PostCSS 插件为所有 CSS 选择器类和 id 添加前缀。

用法

使用PostCSS cli

安装postcss-clipostcss-prefixer在您的项目目录中:

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

在你的 package.json

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

其他

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

选项

字首

Type: `string`<br>
Default: none

用作前缀的字符串

忽视

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

插件忽略的选择器数组,接受字符串和正则表达式。

例子

插件生成的结果的使用示例。

代码

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);

输入:

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

输出:

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

学分

基于thompsongl创建的postcss-class-prefix插件。


推荐阅读