【问题标题】:How do I parse CSS to prefix CSS selectors如何解析 CSS 以添加 CSS 选择器前缀
【发布时间】:2018-11-07 07:17:56
【问题描述】:

我有以下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 配置)

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

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

非常欢迎任何帮助,并在此先感谢您! :-)

【问题讨论】:

  • 看起来一个简单的正则表达式替换就可以解决这个问题,您是否遇到了任何特定的障碍?
  • 不确定 CSS 字符串上的简单 RegEx 是否是安全解决方案,因为我正在寻找通用解决方案(请参阅编辑后的 ​​OP)。我担心 replace .XXX with .prfx-XXX 之类的东西可能会影响文件中出现的 .XXX 不一定是类 CSS 选择器,但可能是 [attribute] 值或 content CSS 属性的值或其他。跨度>
  • 上下文选择器不够用?喜欢.prfx .a { ... }?您希望像 #d .a[href⁼https] > .icon-link { ... } 这样的复合选择器会发生什么?
  • 不,恐怕它必须是文件中每个 CSS 选择器中使用的每个类名的前缀

标签: css node.js parsing


【解决方案1】:

您可能想查看https://github.com/marceloucker/postcss-prefixer#postcss-prefixer

postcss 前缀

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 */
}

学分

插件基于postcss-class-prefixthompsongl创建。

【讨论】:

猜你喜欢
  • 2015-10-11
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 2014-02-21
  • 2020-12-20
  • 2013-07-27
  • 2012-04-28
  • 2011-03-21
相关资源
最近更新 更多