【发布时间】:2015-02-11 05:44:02
【问题描述】:
我要做的是使用 Gulp 在 php 文件中缩小内联 javascript <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
?>
【问题讨论】:
-
一般情况下是无法做到的。
-
我不得不问...为什么不呢? @zerkms
-
因为通常结果取决于 php 运行时。
-
但这需要吗?我在考虑仍然保留 php 变量,只是将内容保存回 php 文件。没有编译实际的 php。
-
这可能是可能的——但我怀疑 gulp 是否能够处理这个问题。您必须编写自己的版本来“识别” JS 代码中的 PHP 变量,并且知道必须让它们“保持不变”。另外,根据您的 PHP 代码,这可能会引入合理的解析器根本无法处理的复杂性。
标签: javascript php gulp