gulp-include-sources
Version:
Includes source files listed in HTML comments
103 lines (83 loc) • 2.88 kB
JavaScript
/**
* Created by Georgi Yanev on 28.01.2017
*/
var gutil = require("gulp-util");
var fs = require("fs");
var path = require("path");
var globby = require("globby");
var extend = require("extend");
const DEFAULT_OPTIONS = {
includesDir: "./",
prefix: "<!-- ",
suffix: " -->",
debug: false,
pathPrefix: "",
templates: {
"js": '<script src="{filePath}"></script>',
"css": '<link rel="stylesheet" type="text/css" href="{filePath}" />'
}
};
function main(filePath, customOptions) {
var options = extend({}, DEFAULT_OPTIONS, customOptions);
var includePath;
if (options.includesDir != "./") {
includePath = path.resolve(options.includesDir);
} else {
includePath = path.dirname(filePath);
}
var includeRegExp = new RegExp(options.prefix + "\\s*include:\\s*(.*)+\\s*" + options.suffix, "g");
gutil.log(gutil.colors.green("[Processing]"), filePath);
function createReplaceFn(replacement, ignore) {
return function () {
if(ignore) {
return replacement;
}
return options.pathPrefix + replacement;
};
}
function toJSONString(string) {
return "{" + string.substring(options.prefix.length + "include:".length).slice(0, -options.suffix.length) + "}";
}
var elementsCount = 0;
function include(contents) {
var matches = contents.match(includeRegExp);
var files;
if (matches == undefined) {
gutil.log(" ", gutil.colors.yellow("[Warning]"), "No matches found.");
return contents;
}
for (var i = 0; i < matches.length; i++) {
var match = matches[i];
var config = JSON.parse(toJSONString(match));
var settings = {
cwd: includePath
};
files = globby.sync(config.files, settings);
var includesProcessed = "";
if (options.debug) {
for(var fileIndex = 0; fileIndex < files.length; fileIndex++) {
gutil.log( gutil.colors.yellow("[DEBUG]"), files[fileIndex]);
}
}
for (var j = 0; j < files.length; j++) {
var template = options.templates[config.type];
elementsCount++;
includesProcessed += template.replace("{filePath}", createReplaceFn(files[j]));
if(files.length > 1) {
includesProcessed += "\n";
}
}
if (includesProcessed != "") {
contents = contents.replace(match, createReplaceFn(includesProcessed, true));
} else {
gutil.log(" ", gutil.colors.red("[Warning]"), "Some files couldn't be found. Leaving comment untouched.");
}
}
return contents;
}
var contents = fs.readFileSync(filePath, "utf8");
contents = include(contents);
gutil.log(" ", elementsCount + " element(s) were added");
return contents;
}
module.exports = main;