UNPKG

lilacs

Version:

A web frontend building tool for teamwork, with automaticly compiling, merging, minifying, syncing files to server, supporting distributed servers, ensuring css or html files' inline reference with correct absolute path, and more.

72 lines (52 loc) 2.25 kB
'use strict'; var path = require('path'); var gutil = require('gulp-util'); var through = require('through2'); var url = require('url'); module.exports = function (options) { var contents, mainPath, reg, asset, assetAbsolute, cdn, testExtReg1, testExtReg2; var defaultExts = 'jpg|jpeg|png|gif|js|css|ico|cur'; var exts = options.exts ? options.exts.join('|') : defaultExts; cdn = options.cdn; if(!/\/$/.test(cdn)){ cdn = cdn + '/'; } asset = options.asset || process.cwd(); assetAbsolute = path.resolve(asset); reg = new RegExp('["\'\\(]\\s*([^\\)"\']*\\.('+ exts +')[^\\)"\']*\\s*)[\\)"\']', 'gim'); return through.obj(function (file, enc, callback) { if (file.isNull()) { this.push(file); return callback(); } if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-cdn-absolute-path', 'Streams are not supported!')); return callback(); } mainPath = path.dirname(file.path); contents = file.contents.toString().replace(reg, function(content, filePath){ // 如果是链接,不更改 if (filePath.slice(0, 7) == 'http://' || filePath.slice(0, 8) == 'https://' || filePath.slice(0, 2) == '//') { return content; } testExtReg1 = new RegExp('\\.(' + exts + ')[^\\w\\./]', 'gi'); // char.js testExtReg2 = new RegExp('\\.(' + exts + ')$', 'gi'); // char.js?param // 匹配不到文件类型,如 /chart.js/a, /dir/file.jsp if (!testExtReg1.test(filePath) && !testExtReg2.test(filePath)) { return content; } var relative; if(/^\//.test(filePath)){ relative = filePath.replace(/^\//, ''); }else{ if(mainPath.indexOf(assetAbsolute) !== -1){ relative = path.relative(asset, path.resolve(asset, mainPath, filePath)); } } return relative ? content.replace(filePath, url.resolve(cdn, relative)) : content; }); file.contents = new Buffer(contents); this.push(file); return callback(); }); };