当前位置: 首页 > news >正文

将css文件中的px转化为rem

pxToRem.js

/*** 使用方式:* 与引入的文件放在同一目录下进行引用配置,执行:node (定义的文件)*/
const fs = require('fs')
const path = require('path')
/*** entry:入口文件路径 type:Strng* pxtopx:以倍数转化px数值,计算方式为除法 ,type:Boolean* pxtorem:以倍数转化rem数值,计算方式为除法 ,type:Boolean* baseNumber:指定除数的基数,type:Number* includeFileTypeList:指定包含的文件类型后缀,type:Array* excludeFile:不包括的文件,可以是路径,type:Array*/
class pxToRemUtil {/*** @type {entry: String, pxtopx: boolean, pxtorem: boolean, baseNumber: number, includeFileTypeList: Array, excludeFile: Array}* @param {初始化参数} option*/constructor(option) {if (!option) {this._logError('请传入配置参数')process.exit(0)}if (!option.entry || !option.entry.trim()) {this._logError('未指定入口文件,请指定')process.exit(0)}if (!option.pxtopx && !option.pxtorem) {this._logError('未指定pxtopx或者pxtorem,检查配置')process.exit(0)}if (!option.baseNumber) {this._logError('未指定基数')process.exit(0)}if (option.pxtopx && option.pxtorem) {this._logError('未指定pxtopx或者pxtorem错误,检查配置')process.exit(0)}this._beginPath = option.entrythis._pxtopx = option.pxtopxthis._pxtorem = option.pxtoremif (this._pxtopx) this._unit = 'px'if (this._pxtorem) this._unit = 'rem'this.BASENUMBER = option.baseNumberthis._includeFileTypeList = option.includeFileTypeList || []this._excludeFile = option.excludeFile || []this._timer = nullthis._fileNumber = 0this._writeFileTimer = nullthis._arr = []this.getRegFile()this.sureHandler()}getRegFile() {let _strconnect = ''this._includeFileTypeList.forEach(item => {_strconnect += `(${item})$|`})_strconnect = _strconnect.length > 1 ? _strconnect.slice(0, _strconnect.length - 1) : ''_strconnect = this._includeFileTypeList.length > 0 ? '^.+' + _strconnect : ''this.regFile = new RegExp(_strconnect)}sureHandler() {process.stdin.setEncoding('utf8')process.stdout.write('此操作不可逆,确认是否进行(Y/n)?')process.stdin.on('data', input => {input = input.toString().trim()if (['Y', 'y', 'YES', 'yes'].indexOf(input) > -1 || !Boolean(input)) {this.fileDisplay(this._beginPath, this.changeFile.bind(this))}if (['N', 'n', 'NO', 'no'].indexOf(input) > -1) process.exit(0)})}fileDisplay(url, cb) {const filePath = path.resolve(url)fs.readdir(filePath, (err, files) => {if (err) return console.error('Error:(spec)', err)files.forEach(filename => {const filedir = path.join(filePath, filename)fs.stat(filedir, (eror, stats) => {if (eror) return console.error('Error:(spec)', err)const isFile = stats.isFile()const isDir = stats.isDirectory()if (isFile) {let exclude = this._excludeFile.some(item => {return filedir.includes(item)})let checkIsImage = filedir.match(/\.(png|jpg|gif|jpeg|webp|ttf|svg)$/)if (filedir.match(this.regFile) && !exclude && !checkIsImage) {this._arr.push({modified: false,path: filedir.replace(__dirname, '').replace(/\\/gim, '/'),})}if (this._timer) clearTimeout(this._timer)this._timer = setTimeout(() => cb && cb(this._arr), 200)}// 如果是文件夹if (isDir) this.fileDisplay(filedir, cb)})})})}changeFile() {/**重新写入文件 替换掉文件的px数值 */const self = thisthis._arr.forEach(item => {fs.readFile('.' + item.path, (err, data) => {let result = data.toString()var reg = /(\-|- |\+ )?([0-9]*\.[0-9]*|\d)+(px\)?)/gilet newStr = result.replace(reg, function (_x) {item.modified = truelet n = _x.search(/px\)/) >= 0 ? 'px\\)' : 'px'let reg = new RegExp(eval(`/(- |\\+ )+([0-9]*\\.[0-9]*|\\d)+${n}/gi`))if (_x.match(reg)) {let C = ''if (_x.search(/\+/) >= 0) {C = '+'} else if (_x.search(/\-/) >= 0) {C = '-'}if (_x.search(/px\)/)) _x = _x.replace(/(- |\+ )/, '').replace(/px/i, '')if (_x.search(/\)/) >= 0) return `${C} ` + parseFloat(_x) / self.BASENUMBER + `${self._unit})`if (!_x.search(/\)/) >= 0) return `${C} ` + parseFloat(_x) / self.BASENUMBER + `${self._unit}`}return parseFloat(_x) / self.BASENUMBER + `${self._unit}`})const opt = {flag: 'w',}if (newStr) {fs.writeFile('.' + item.path, newStr, opt, (err, success) => {if (this._writeFileTimer) clearTimeout(this._writeFileTimer)this._writeFileTimer = setTimeout(() => {this._logSuccess(self._fileNumber + ' 个文件写入成功')process.exit(0)}, 200)if (err) {this._logError(err)process.exit(0)} else {if (item.modified) {self._fileNumber++this._logSuccess('更改并写入:' + item.path.slice(1) + ' 成功')}}})}})})}_logSuccess(str) {console.log('\x1B[32m%s\x1B[39m', str)}_logError(str) {console.log('\x1B[31m%s\x1B[39m', str)}
}
module.exports = pxToRemUtil 

execFile.js

//将上面文件引入
let pxToRemUtil = require('./pxToRemUtil')/*** 接受的参数含义* entry:入口文件路径 type:Strng* pxtopx:以倍数转化px数值,计算方式为除法 ,type:Boolean* pxtorem:以倍数转化rem数值,计算方式为除法 ,type:Boolean* baseNumber:指定除数的基数,type:Number* includeFileTypeList:指定包含的文件类型后缀,type:Array* excludeFile:不包括的文件,可以是路径,type:Array*/
new pxToRemUtil({entry:'./',//需要修改的文件入口pxtorem:true,//设置为px转rembaseNumber:100,//将整体的数值除100,例如10px变成0.1remexcludeFile:[''],//可选值,排除的文件名includeFileTypeList:['.vue','.css']//可选值,包含改那些文件的后缀list
})

然后再控制台中执行:

node execFile.js

http://www.lryc.cn/news/111421.html

相关文章:

  • JNI之Java实现远程打印
  • YOLOv5基础知识入门(2)— YOLOv5核心基础知识讲解
  • 免费的scrum敏捷开发管理工具
  • Hive创建外部表详细步骤
  • leetcode 452. 用最少数量的箭引爆气球
  • Pytorch Tutorial【Chapter 3. Simple Neural Network】
  • 2.虚拟机开启kali_linux
  • 【StyleGAN2论文精读CVPR_2020】Analyzing and Improving the Image Quality of StyleGAN
  • 医学图像处理
  • PyCharm安装使用2023年教程,PyCharm与现流行所有编辑器对比。
  • vue3中CompositionApi理解与使用
  • 【前瞻】视频技术的发展趋势讨论以及应用场景
  • Visual Studio在Debug模式下,MFC工程中包含Eigen库时的定义冲突的问题
  • Java实现购买机票案例
  • 通用FIR滤波器的verilog实现(内有Lowpass、Hilbert参数生成示例)
  • 有利于提高xenomai /PREEMPT-RT 实时性的一些配置建议
  • 【LeetCode】24.两两交换链表中的节点
  • 融合大数据、物联网和人工智能的智慧校园云平台源码 智慧学校源码
  • Spring Boot通过切面实现方法耗时情况
  • 深挖 Threads App 帖子布局,我进一步加深了对CSS网格布局的理解
  • leetcode做题笔记54
  • GD32F103VE点灯
  • matlab使用教程(8)—绘制三维曲面图
  • 【Nginx14】Nginx学习:HTTP核心模块(十一)其它配置
  • 243. 一个简单的整数问题2(树状数组)
  • C#利用自定义特性以及反射,来提大型项目的开发的效率
  • 【传统视觉】C#创建、封装、调用类库
  • AutoMapper反向映射
  • 华为Mate30报名鸿蒙 HarmonyOS 4.0.0.108 系统更新
  • elementui Cascader 级联选择使用心得