-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
gulp #3
Comments
这个正则有问题,容易误判 |
|
@island205 看看我的 var fs = require("fs");
fs.readFile("index.html", "utf8", filterFile);
function filterFile(error, data) {
if (error) {
throw error;
}
var newData = removeLinkTags(data);
fs.writeFile("index.html", newData, function(err) {
console.log("File Saved !"); //文件被保存
});
}
function removeLinkTags(data) {
var b = /<link[^>]*rel(\s)*=(\s)*[\'\"]stylesheet[\'\"][^>]*>/gi, newData;
return data.replace(b, '');
} |
用 var domStr = ''
+ '<meta content="telephone=no" name="format-detection" />'
+ '<link rel="shortcut icon" href="//static.lufaxcdn.com/config/images/favicon-new.ico" />'
+ '<link type="text/css" rel="stylesheet" href="//static.lufaxcdn.com/lufax-public/base/base.1c52d4c1.css"/>'
var parse5 = require('parse5')
var domTree = parse5.parse(domStr)
var treeAdapter = parse5.treeAdapters.default
function isLinkCss(dom) {
if (dom.nodeName != 'link') return false
var attrs = dom.attrs
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i]
if (attr['name'] === 'type' && attr['value'] === "text/css") {
return true
}
}
return false
}
function removeLink(dom) {
if (isLinkCss(dom)) {
treeAdapter.detachNode(dom)
} else {
for (var i = 0; i < dom.childNodes.length; i++) {
removeLink(dom.childNodes[i])
}
}
}
removeLink(domTree)
console.log(parse5.serialize(domTree)) |
@island205 第一次写gulp插件 const Stream = require('stream');
const gutil = require('gulp-util');
const Bufferstreams = require('bufferstreams');
function gulpReplaceCssLink() {
const PLUGIN_NAME = 'gulp-replace-css-link';
const replaceReg = /\s*<link.+?rel\s*=\s*[\'\"]stylesheet[\'\"].*?(?:\/)?>/gi;
return new Stream.Transform({
objectMode: true,
transform: function transfrom(file, encoding, cb) {
const source = file;
function replace(input) {
return new Buffer(input.replace(replaceReg, ''));
}
if (file.isBuffer()) {
source.contents = replace(String(file.contents));
} else if (file.isStream()) {
source.contents = file.contents.pipe(new Bufferstreams((err, buffer, callback) => {
if (err) {
callback(new gutil.PluginError(PLUGIN_NAME, err));
}
const transformed = replace(buffer.toString());
callback(null, transformed);
}));
}
cb(null, source);
}
});
}
module.exports = gulpReplaceCssLink; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
是不是直接用replace插件就OK了。。。
The text was updated successfully, but these errors were encountered: