我想做的是使用Gulp压缩php文件中的内联javascript
我已经使用
我的想法是保留php变量并将内容保存回php文件中,而不是编译实际的php。 插件代码:
<script>
。原因是我想压缩整个文件的大小(在我的情况下确实很重要)。javascript包含php变量。我已经使用
gulp-minify-inline-scripts
插件开始了这项工作,但更改了它,以便识别php文件。不幸的是,除非使用html文件,否则我无法成功输出javascript。我的想法是保留php变量并将内容保存回php文件中,而不是编译实际的php。 插件代码:
var path = require('path');
var gutil = require('gulp-util');
var uglify = require('uglify-js');
var through = require('through2');
var PLUGIN_NAME = 'gulp-minify-inline-scripts';
module.exports = function (options) {
return through.obj(function (file, enc, cb) {
var self = this;
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return cb();
}
var fileName = file.path.split(path.sep).pop();
//html file only
if (!/^\.php?$/.test(path.extname(file.path))) {
gutil.log(gutil.colors.red('[WARN] file ' + fileName + ' is not a html file'));
this.push(file);
return cb();
}
gutil.log("uglify inline scripts in html file: " + file.path);
var html = file.contents.toString('utf8');
var reg = /(<script(?![^>]*?\b(type=['"]text\/template['"]|src=["']))[^>]*?>)([\s\S]*?)<\/script>/g;
html = html.replace(reg, function (str, tagStart, attr, script) {
try {
var result = uglify.minify(script, { fromString: true });
return tagStart + result.code + '</script>';
} catch (e) {
self.emit('error', new gutil.PluginError(PLUGIN_NAME, 'uglify inline scripts error: ' + (e && e.stack)));
}
});
file.contents = new Buffer(html);
this.push(file);
cb();
});
};
将PHP内联Javascript压缩:
<?php
/* Start: This is a php file
?>
<script>
<?php $var = 'test'; ?>
A.config = {
test: '<?php echo $var; ?>'
};
a.visible = function (image, distance) {
var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
var bounds;
var gap;
if (!image.getBoundingClientRect) {
return false;
}
};
</script>
<?php
/* End: This is a php file
?>