javascript 产生-icons.js

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 产生-icons.js相关的知识,希望对你有一定的参考价值。

const fs = require('fs');
const path = require('path');
const fx = require('mkdir-recursive');

const iconFolder = './src/content/app/fx/icons/'
const svgFolder = `${iconFolder}svg/`;
const shortSvgFoler = '/fx/icons/svg/'

/**
 * source: Folder where the icon are
 * cssfilename: Filename of the css file
 * cssprefix: Prefix to add on css class
 */
const ICONS = [
  {
    source: './src/content/app/icons/',
    cssfilename: '_icons-mobile.scss',
    cssprefix: '.icon-mobile-',
  },
];

// Create the svg folder if it doesn't exist yet
if (!fs.exists(svgFolder)) {
  fx.mkdir(svgFolder, error => {
    if (error) {
      return console.log('error', error);
    }

    console.log('SVG folder ahs been created in: ', svgFolder);
    addIcons();
  });
} else {
  addIcons
}

function addIcons() {
  try {
    ICONS.forEach(icon => {
      let backgroundSVG = '';
      let numberOfIcons = 0;
  
      fs.readdirSync(icon.source).forEach(file => {
        copyFile(icon.source, svgFolder, file);
  
        backgroundSVG += createCssAttr(shortSvgFoler, file, icon.cssprefix);
  
        numberOfIcons++;
      });
  
      fs.writeFile(iconFolder + icon.cssfilename, backgroundSVG, error => {
        if (error) {
          return console.log('Error 3: ', error);
        }
        console.log(`${numberOfIcons} icons have been added!`);
      });
    });
  } catch (error) {
    console.log('Error 1: ', error);
  }
  
}

/**
 * Add CSS attribute into the class
 * @param {String} source 
 * @param {String} filename 
 * @param {String} prefix 
 */
function createCssAttr(dest, filename, prefix) {
  const filenameWithoutExtension = path.basename(filename, '.svg');
  return `${prefix}${filenameWithoutExtension} {
  background-image: url('${dest + filename}');
  background-repeat: no-repeat;
}\n`;
}

/**
 * Copy icons into a new folder in destination path
 * @param {String} source 
 * @param {String} dest 
 * @param {String} file 
 */
function copyFile(source, dest, file) {
  try {
    fs.createReadStream(source + file).pipe(fs.createWriteStream(dest + file));
  } catch (error) {
    console.log('Error 2: ', error);
  }
}

以上是关于javascript 产生-icons.js的主要内容,如果未能解决你的问题,请参考以下文章

tinymce 使用 报错 icons.js Unexpected token ‘<‘

nodejs---修改文件名字

JavaScript-04-JS产生对象以及批量产生对象

JavaScript 中的 null 比较会产生啥强制?

为啥 .NET 中的 AEC 加密产生与 JavaScript 不同的结果?

哪个 javascript 缩小库产生更好的结果? [关闭]