gulp-nube-inject
Version:
gulp plugins for html template js or css inject
72 lines (56 loc) • 1.73 kB
JavaScript
'use strict';
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var through = require('through2');
var Path = require('path');
var PLUGIN_NAME = 'gulp-nube-inject';
var RE_NUBE_INJECT = /\<\!\-\-\s*Nube\-Inject\s*\:((.*)\.(.*))\s*\-\-\>[\s\S]+?\<\!\-\-\s*Nube\-Inject\-End\s*\-\-\>/gm;
var HTML = {
'scss|less|css' : '<link type="text/css" rel="stylesheet" href="<%=src%>">',
'js|coffee|ts' : '<script type="text/javascript" src="<%=src%>"></script>'
};
/////////////////////////////////////
// Main Gulp Nube Pullout function //
/////////////////////////////////////
module.exports = function(manifest) {
function replacement(source, _tempContents) {
return _tempContents.replace(RE_NUBE_INJECT, function($1, $2, $3, $4) {
var paths = Path.parse(source);
paths.name = $3;
paths.base = $2;
return tagFactory($4, Path.format(paths));
});
}
// <link> ==> .scss|.less|.css
// <script> ==> .js|.coffee|.ts
function tagFactory(ext, pathKey) {
var src = Path.relative(Path.parse(pathKey).dir, manifest[pathKey.trim()] || ""),
tmpl = "";
if (src) {
for (var i in HTML) {
if (HTML.hasOwnProperty(i) && i.split('|').indexOf(ext.trim()) > -1) {
tmpl = HTML[i];
}
}
if (tmpl) {
return tmpl.replace(/\<\%\=\s*src\s*\%\>/gm, src);
} else {
return "";
}
}
return "";
}
return through.obj(function(file, enc, cb) {
var _tempContents = "",
paths = null;
if (file.isNull()) {
return cb();
}
if (file.isStream()) {
return cb(new PluginError(file, "Streaming not supported"));
}
_tempContents = replacement(file.relative, file.contents.toString());
file.contents = new Buffer(_tempContents);
cb(null, file);
});
};