css - 如何解析 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 配置)
但我想知道是否有更好/更安全的解决方案已经过测试/成为标准做法?
注意: 以上文件内容只是一个示例。我正在寻找一种方法来实现我完全不知道其内容的文件。所以我正在寻找一个“通用”的解决方案。
任何帮助都将受到欢迎,并在此先感谢您!:-)
解决方案
您可能需要检查https://github.com/marceloucker/postcss-prefixer#postcss-prefixer。
postcss 前缀
PostCSS 插件为所有 CSS 选择器类和 id 添加前缀。
用法
使用PostCSS cli:
安装
postcss-cli
并postcss-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插件。
推荐阅读
- css - 在 Boostrap 导航栏的角度组件中覆盖 styles.css
- python - 如何在 Mac OS 上使用 Tkinter 获取黑色文件对话框?
- c++ - 如何使用 fmod(浮点数)检查 - 并获得余数?
- python - 将 CSV 文件读入 Numpy 数组
- c# - ASP.Net MVC C# 分配角色关闭复选框和用户列表
- ios - VisualStudio 2017 for Mac - iOS 模拟器启动但不运行应用程序
- c# - 在并发线程上管理任务取消和完成
- ios - Environment.SpecialFolder.MyDocuments 中的 CreateDirectory 被拒绝
- php - 我如何才能为 foreach 中的第二个返回创建自定义变量
- angular - 如何在 Angular Ionic 4 中正确实现来自 Dataservice 的 getPosts?