Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env node
- const program = require('commander')
- const fsp = require('fs').promises
- const path = require('path');
- const chalk = require('chalk')
- const globby = require("globby");
- const cheerio=require('cheerio');
- const css = require('css');
- program
- .version('0.0.1')
- .description('svg图标生成脚本 by syrxw')
- .option('-g, --generate', '生成')
- const svgFilePath = path.resolve("client/static/icons.svg");
- const dir = path.resolve("client/assets/image/svg_icons");
- const filePahts = globby.sync(["**/*.svg"], { cwd: path.resolve("client/assets/image/svg_icons") })
- let svgFile = null;
- function splitFileName(text) {
- var pattern = /\.{1}[a-z]{1,}$/;
- if (pattern.exec(text) !== null) {
- return (text.slice(0, pattern.exec(text).index));
- } else {
- return text;
- }
- }
- // 生成css AST语法树
- function parseCSS(content){
- const obj = css.parse(content)
- const rules = obj.stylesheet.rules
- return rules.map(item => {
- return {
- selector: item.selectors[0],
- declarations: item.declarations.map(kitem => {
- return {
- property: kitem.property,
- value: kitem.value
- }
- })
- }
- })
- }
- // 读取svg文件
- async function readSvgFile(){
- try{
- const data = await fsp.readFile(svgFilePath)
- svgFile = cheerio.load(data,{ xmlMode: true });
- }catch(err){
- console.log(chalk.red('icons.svg文件不存在或文件损坏'))
- return false;
- }
- }
- async function readSvgIcons(){
- try{
- svgFile('defs').html("")
- for(const file of filePahts){
- const data = await fsp.readFile(path.join(dir,file))
- const $ = cheerio.load(data,{ xmlMode: true });
- const fileName = splitFileName(file)
- if($('path').length < 1){
- return false
- }else{
- if($('style').length>0){
- const parsrCssRst = parseCSS($('style').html())
- parsrCssRst.forEach(item =>{
- item.declarations.forEach(declar => {
- $(item.selector).attr(declar.property,declar.value)
- })
- })
- }
- const element = `<symbol id="icon-${fileName}" viewBox="0 0 200 200">${$('path')}</symbol>`
- svgFile('defs').append(element)
- }
- }
- }catch(err){
- console.log(chalk.red(err))
- return false;
- }
- }
- async function writeIconFile(){
- try{
- await fsp.writeFile(svgFilePath,svgFile.root().html())
- }catch(err){
- console.log(chalk.red(err))
- return false;
- }
- }
- async function main(){
- try{
- await readSvgFile();
- }catch(e){
- console.log(chalk.red(err))
- }
- try{
- await readSvgIcons();
- }catch(e){
- console.log(chalk.red(err))
- }
- try{
- await writeIconFile();
- }catch(e){
- console.log(chalk.red(err))
- }
- }
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement