iconfont SVG 圖標庫 生成 react-native-svg所需的格式

const fs = require('fs');
const path = require('path');

const filePath = `${path.resolve('fontsvg')}/build`
//判斷文件夾是否存在
const isDirectory = (filePath) =>{
  return new Promise((resolve,reject) => {
    fs.access(filePath, (err) => {
      if(err){
        resolve('faild')
      }
      resolve('ok')
    })
  })
}

//創建文件夾
const creactMkdir = (filePath) =>{
  return new Promise((resolve,reject) => {
    fs.mkdir(filePath, (err) => {
      if(err){return}
      resolve(true)
    })
  })
}

const writeSvg = (filePath) => {
  console.log('讀取處理中...')
  fs.readFile(`${path.resolve('fontsvg')}/iconfont.js`, 'utf8', (err, data) => {
    if (err) {
    } else {
      const svgArr = data.split('</symbol>');
      svgArr.pop();
      let svgTmp = '';
      let viewBox = '';
      svgArr.forEach((svg) => {
        const tmpPath = svg.split('<path');
        const viewBoxKey = tmpPath[0].match('id=.*"')[0].split('"')[1].replace('icon-', '').replace(/-(\w)/g, x => x.slice(1).toUpperCase());
        const viewBoxValue = tmpPath[0].match('viewBox=.*"')[0].split('"')[1];
        if (viewBoxValue !== '0 0 1024 1024') {
          viewBox[viewBoxKey] = viewBoxValue;
          viewBox += `    ${viewBoxKey}: '${viewBoxValue}',\n`;
        }
        const pathArr = [];
        tmpPath.shift();
        tmpPath.forEach((path) => {
          pathArr.push(`{${path.replace(/=/g, ': ').replace('fill', ', fill').replace('></path>', '')}}`);
        });
        svgTmp += `  ${viewBoxKey}: [${pathArr}],\n`;
      });
      const svgStr = `export default {\n${svgTmp}\n}`;
      fs.writeFile(`${filePath}/iconfont.svg.js`, svgStr, 'utf8',() => {
        if (err) return
        console.log('寫入成功')
      });
    }
  })
}

async function WriteFontSvg () {
  const directory = await isDirectory(filePath)
  if(directory == 'ok'){
    writeSvg(filePath)
  }else{
    const creact= await creactMkdir(filePath)
    if(creact){
      console.log('創建成功')
      writeSvg(filePath)
    }
  }
}

WriteFontSvg()


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章