From 27494d06c188a031764f5e3a20e5be4fd42a7b5b Mon Sep 17 00:00:00 2001 From: zhaoluming Date: Tue, 10 May 2016 16:27:28 +0800 Subject: [PATCH] add support of stylus,ejs,html --- index.js | 60 +++++++++++++++++++++++++++++++++++++++++++++++++--- package.json | 4 ++++ 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 5729fe0..77e5bfc 100644 --- a/index.js +++ b/index.js @@ -1,12 +1,66 @@ var through = require("through2") var gutil = require("gulp-util") +var minify = require('html-minifier').minify var fs = require("fs") module.exports = function (options) { return through.obj(function (file, enc, cb) { - var contents = file.contents.toString(enc) - contents.replace(/require\((["'])([\.\w\d\/]+)\1\)/g, function(req, quote, url) { - fs.readFileSync(url, "utf8", callback) + var baseArr = file.base.split(/\/|\\/) + baseArr.pop() + var contents = file.contents.toString(enc).replace(/require\((["'])([\.\w\d\/]+)\1\)/g, function(req, quote, rawUrl) { + var urlArr = rawUrl.split("/") + var fileName = urlArr[urlArr.length-1] + if (fileName.split(".").length >= 2) { + var suffix = fileName.split(".").pop() + } else { + return req + } + var url + switch (urlArr[0]) { + case ".." : + baseArr.pop() + for (var i = 1; i < urlArr.length; i++) { + if (urlArr[i] == "..") { + baseArr.pop() + } else { + baseArr.push(urlArr[i]) + } + } + url = baseArr.join("/") + break; + case "." : + urlArr.shift() + url = file.base + urlArr.join("/") + break; + default : + new gutil.PluginError({ + plugin: 'module-bundler', + message: 'unsupported url' + }); + } + gutil.log(url) + if (url) { + var text = fs.readFileSync(url, "utf8") + switch (suffix) { + case "html": + case "ejs": + text = minify(text, {collapseWhitespace:true}) + break; + case "styl": + var stylus = require('stylus') + stylus.render(text, {compress: true}, function(err, css) { + text = css + }) + break; + default: + return req + } + return "\"" + text.replace(/"/g, "\\\"") + "\"" + } else { + return req + } }); + file.contents = new Buffer(contents, enc); + cb(null, file, enc) }); }; diff --git a/package.json b/package.json index c95a44d..aea7105 100644 --- a/package.json +++ b/package.json @@ -17,8 +17,12 @@ "license": "MIT", "dependencies": { "gulp-util": "^3.0.7", + "html-minifier": "^2.1.2", "through2": "^2.0.1" }, + "peerDependencies": { + "stylus": "*" + }, "devDependencies": { "gulp": "^3.9.1", "mocha": "^2.4.5"