Skip to content

Instantly share code, notes, and snippets.

@mritzco
Last active February 24, 2017 08:33
Show Gist options
  • Save mritzco/670156735ef07ab9010acb97184b8fa5 to your computer and use it in GitHub Desktop.
Save mritzco/670156735ef07ab9010acb97184b8fa5 to your computer and use it in GitHub Desktop.
Using NPM as a build tood
{
"fileExtensions": [".less", ".css"],
"excludedFiles": ["src/less/*.less"],
"spaceAfterPropertyColon": {
"enabled": true,
"style": "one_space" // Comments are allowed
},
"maxCharPerLine": 999999,
"spaceAfterPropertyColon": "no_space",
"urlQuotes": false,
"finalNewline": false,
"propertyOrdering": false,
"stringQuotes": false,
"importPath": {
"filenameExtension": true
},
"zeroUnit": "style",
"hexLength": "short",
"newlineAfterBlock": false,
"hexNotation": "lowercase",
"emptyRule": true,
"importantRule": false,
"trailingWhitespace": false
}
/* jshint esversion: 6 */
var fs = require('fs');
var path = require('path');
var walk = require('../build_scripts/walksync.js');
/**
* function to encode file data to base64 encoded string
* @method base64_encode
* @param {string} file Binary file to read and encoded
* @return {string} base64 encoded data
*/
function base64_encode(file) {
// read binary data
let bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
/**
* function to create file from base64 encoded string
* @method base64_decode
* @param {String} base64str Encoded str
* @param {String} file File to write with decoded data
* @return {null}
*/
function base64_decode(base64str, file) {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
let bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
}
/**
* Returns a fixed length string
* @method fix
* @param {integer} len Fixed length of string
* @param {String} msg String to convert into a fixed length
* @param {String} [chr=" "] Character to use for padding
* @return {String} padded string
*/
function fix(len, msg, chr=" "){
return chr.repeat(len-msg.length) + msg;
}
/**
* Save a file css definition
* @method imgCSS
* @param {String} file Full path to file to encoded
* @param {Object} options {css: "css prefix", dest: "saving path "}
* @return {null} nothing
*/
function imgCSS(file, options) {
let destName = options.prefix + path.parse(file).name;
let target = path.join(options.dest, destName + ".css");
try {
let enc = base64_encode(file);
let css = `.${options.prefix+destName} {\n\tbackground:url(data:image/png;base64,${enc}) no-repeat left center;\n}`;
fs.writeFileSync(target, css, "utf8");
} catch (e) {
console.log(' ERROR processing: %s => %s',file, fix(20, destName));
} finally {
console.log(' %s => %s(%s bytes)',
fix(30, file),
fix(30,destName),
fs.statSync(target).size
);
}
}
/**
* Process command line params
*/
var arg = require('minimist')(process.argv.slice(2), { '--': true});
if (!arg.src || !arg.dest) {
console.log("Missing arguments, usage: node icons64.js --src [srcdir] --dest [destdir]");
}
console.log("Destination: %s", arg.dest);
// Make an options object
const options = {
prefix: arg.prefix || "",
dest: arg.dest
};
// Get a list of files and process
const files = walk.files(arg.src, [], {recursive: false, addPath: true});
files.forEach(file => {
imgCSS(file, options);
});
{
"name": "projectname",
"version": "1.0.0",
"description": "Sample for building with npm",
"main": "index.js",
"config": {
"src": "src/",
"dist": "dist/",
"scripts": "build_scripts",
"lessicons": "src/less_icons",
"svgicons": "dist/svg_icons",
"themes": "dist/themes"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"clean": "echo \" => Cleaning dist/ folder \" && rm -r dist && mkdir dist",
"prethemes": "echo \"=> Cleaning folders \" && rm -rf $npm_package_config_themes && mkdir $npm_package_config_themes && npm run lint:less",
"lint:less": "echo \"=> Linting less \" && lesshint src",
"themes": "echo \"=> Processing theme files $npm_package_config_themes \" && for file in src/themes/*.less; do lessc $file $npm_package_config_themes/`basename $file | sed -e 's/.less/.css/'` ; done",
"modules": "echo \"=> Processing private_module less\" && for file in src/less_modules/*.less; do lessc $file dist/modules/`basename $file | sed -e 's/.less/.css/'` ; done",
"preicons": "echo \"=> Cleaning ($npm_package_config_lessicons) folder \" && rm -rf $npm_package_config_lessicons && mkdir $npm_package_config_lessicons",
"icons": "echo \"=> Converting png files into base 64\" && node $npm_package_config_scripts/icons64.js --src $npm_package_config_src/icons --dest $npm_package_config_lessicons",
"presvg": "echo \"=> Cleaning ($npm_package_config_svgicons) folder \" && rm -rf $npm_package_config_svgicons && mkdir $npm_package_config_svgicons",
"svg" : "echo \"=> Creating svg store \" && node $npm_package_config_scripts/svgstore.js --src $npm_package_config_src/svg --dest $npm_package_config_svgicons",
"prebuild": "echo \"=> Prebuild: Cleaning \" && npm run clean",
"build": "echo \"=> Building all \" && npm run icons && npm run themes && npm run modules && npm run svg"
},
"author": "itzco",
"license": "ISC",
"devDependencies": {
"less": "^2.7.2",
"lesshint": "^3.0.0",
"minimist": "^1.2.0",
"postcss-cli": "^2.6.0"
},
"dependencies": {
"svgstore": "^2.0.2"
}
}
/* jshint esversion: 6 */
/**
* https://github.com/svgstore/svgstore
*/
var svgstore = require('svgstore');
var fs = require('fs');
var path = require('path');
var walk = require('../build_scripts/walksync.js');
// Parse command line
var arg = require('minimist')(process.argv.slice(2), { '--': true});
if (!arg.src || !arg.dest) {
console.log("Missing arguments, usage: node svgstore.js --src [srcdir] --dest [destdir]");
}
console.log("Destination: %s", arg.dest);
// Actual processing of root dir -> store.svg
const files = walk.files(arg.src, [], {recursive:false, addPath: true});
if (files.length) createStore(files, arg.dest);
// Allow creationg of multiple stores (one per directory)
const dirs = walk.dirs(arg.src);
dirs.forEach(function(item) {
console.log('Processing dir: %s -> %s.svg', item, item);
if (item !== 'store') {
const filesOnly = walk.files(path.join(arg.src, item), [], {recursive:false, addPath: true});
createStore(filesOnly, arg.dest, item);
} else {
console.log('=> Illegal folder name, "store" is reserved for root folder');
}
});
function createStore(files, dest, svgname="store"){
// Extra text for help and readme.md
let help = ["# Using the svg files", "## Styling images:", "````svg { fill: YOURCOLOR; width:30px; }````", "## This svg contains the following images:",
"| Image | HTML |", "|----|-----|"];
let demo = ["<html>\n<head>\n<style type=\"text/css\">\n svg {\n fill: teal;\n width:30px;\n height: 30px;\n }\n</style>\n</head>\n<body><ul>"];
let sprites = svgstore();
files.forEach(function(file) {
let name = path.parse(file).name;
sprites.add(name, fs.readFileSync(file, 'utf8'));
help.push( "|" + name + "|" + '````<svg role="img"><use xlink:href="' + dest + '/store.svg#'+name+'"/></svg>```` |');
demo.push(`<li>${name}: <svg role="img"><use xlink:href="${svgname}.svg#${name}"/></svg></li>`);
});
fs.writeFileSync(path.join(dest, svgname+".svg"), sprites);
// Create help
fs.writeFileSync(path.join(dest, `${svgname}_help.md`), help.join("\n"));
// Create Demo
demo.push("</ul></body>\n\n</html>");
fs.writeFileSync(path.join(dest, `${svgname}_demo.html`), demo.join("\n"));
}
console.log("Done");
/* jshint esversion: 6 */
(function() {
'use strict';
var fs = require('fs');
var path = require('path');
// const walkSync = (dir, filelist = [], recursive = true) =>
// fs.readdirSync(dir)
// .map(file => fs.statSync(path.join(dir, file)).isDirectory() ?
// walkSync(path.join(dir, file), filelist)
// : filelist.concat(path.join(dir, file))[0]);
const opt_dirs = { addPath: false };
const dirs = (dir, options = {}) => {
let opts = Object.assign({}, opt_dirs, options);
let dirlist = [];
fs.readdirSync(dir).forEach(file => {
let fullpath = path.join(dir, file);
if (fs.statSync(fullpath).isDirectory()){
dirlist.push( options.addPath ? fullpath : file );
}
});
return dirlist;
};
const options = {
recursive: true,
addPath : false
};
const allFilesSync = (dir, fileList = [], _opts = {} ) => {
let opts = Object.assign({}, options, _opts);
fs.readdirSync(dir).forEach(file => {
const filePath = path.join(dir, file);
const key = opts.addPath ? filePath : file; // With path
let res = fs.statSync(filePath).isDirectory()
? ( opts.recursive ? {[key]: allFilesSync(filePath, [], opts)} : null)
: key;
if (res) fileList.push(res);
});
return fileList;
};
module.exports = { files: allFilesSync, dirs: dirs };
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment