使用Gulp最小化PHP文件中的内联Javascript

Minify Inline Javascript in PHP Files with Gulp

本文关键字:Javascript 文件 Gulp 最小化 PHP 使用      更新时间:2023-09-26

我要做的是使用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
?>

对于任何遇到这种情况的人,我已经根据@Cbroe在评论中的提示编写了一个解决方案。这真的很简单:包装php代码,这样它就不会破坏jsminifier,然后在代码被缩小后,删除包装的php字符串以释放php变量。您可以通过选择更好的换行字符串来简化这一点。

我只是要小心你使用它的目的,因为除了我的特定用例之外,我还没有测试过其他任何东西。

更新 :我已经用了几个月了,它从未坏过。只需确保使用与regex中相同的脚本标记模式,否则它可能在页面中找不到标记

新Gulp插件代码:

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
                });
                var code = result.code;
                code = code.split("STRIP__>'"").join('');
                code = code.split("'"<__STRIP").join('');
                return tagStart + 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: "<__STRIP'<?php echo $var; ?>'STRIP__>"
    };
    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
?>