UNPKG

diyi-ui

Version:

diyi A Vue.js UI

123 lines (110 loc) 3.73 kB
// 有node环境下 终端命令行 node test.js 【'@/styles/xxxx/xxx.scss'】【newFileName】 // 使用别名@表示根目录下 或者可以使用相对路径 // node addComment.js '@/test.scss' 'a.scss' // filePath 文件所在路径; newFileName 重命名文件(选填) let [filePath, newFileName] = process.argv.splice(2) const path = require('path') const fs = require('fs') if (filePath.indexOf('@') !== -1) { filePath = filePath.replace('@', 'src') } filePath = path.resolve(filePath) console.log('--------') console.log(`filePath: ${filePath}`) console.log('--------') // tag const TAG_REG = /^\s+([a-z]+)/ // .className const TATLE_REG = /\.(.*)\{/ // include [bem](className) const INCLUDE_REG = /\@include\s+([^\(\s]+)/ // &-className const JOINT_REG = /\&([\-\_]+)(.*)\{/ // '{' const LEFT_REG = /\{/ // '}' const RIGHT_REG = /\}/ // 括号内className const BRACKETS_REG = /\(([^)]*)\)/ // 注释 const COMMENT_REG = /(\s+\/\/.*)/ const FUNC_MAP = { b: 'dy-', e: '__', m: '--', s: 'is-' } const selectors = [] function readFile (dir) { const buffer = fs.readFileSync(dir) // 每一行做切割 const bufferList = String(buffer).split('\r') const bableScss = bufferList.map(item => { // 碰到“{”,则入栈一个选择器 if (LEFT_REG.test(item)) { // 以 .开头的类名 和tag打头的 if (item.match(TATLE_REG) || item.match(TAG_REG)) { selectors.push(`${RegExp.$1.trim()}%`) return item } // 以&- 开头的连接类名 if (item.match(JOINT_REG)) { return jointClass(item) } // 带有include if (item.match(INCLUDE_REG)) { return includeClass(item) } selectors.push(`${RegExp.$1.trim()}%`) } // 碰到“}”,则出栈一个选择器 if (RIGHT_REG.test(item)) { selectors.pop() return item } console.log(item) return item }) let newFilePath = filePath if (newFileName) { const fileNameList = filePath.split('\\') fileNameList[fileNameList.length - 1] = newFileName newFilePath = fileNameList.join('\\') } fs.writeFileSync(newFilePath, bableScss.join('\r')) } // 处理含include的 function includeClass (item) { const funcName = RegExp.$1 item.match(BRACKETS_REG) const className = RegExp.$1 const name = (FUNC_MAP[funcName] + className).trim() if (funcName === 'b' || funcName === 's') { selectors.push(`${name}%`) item = item.replace(COMMENT_REG, '') return `${item} // ${name}` } const parent = selectors.join(' ').replace(/\%/g, '') // 所有路径类名拼接的字符串 const totalName = `${parent}${name}` selectors.push(`${totalName}`) const list = totalName.trim().split(' ') item = item.replace(COMMENT_REG, '') return `${item} // ${list[list.length - 1]}` } // 处理&-拼接 function jointClass (item) { if (selectors.length !== 0) { item.match(JOINT_REG) const child = (RegExp.$2).trim() const sign = (RegExp.$1).trim() const parent = selectors.join(' ').replace(/\%/g, '') // 所有路径类名拼接的字符串 const totalName = `${parent}${sign}${child}` const list = totalName.replace(/\s\#/g, '-').trim().split(' ') item = item.replace(COMMENT_REG, '') return `${item} // ${list[list.length - 1]}` } return item } readFile(filePath)