对包含PHP的JavaScript文件使用YUI Compressor [英] Using the YUI Compressor on JavaScript files containing PHP

查看:100
本文介绍了对包含PHP的JavaScript文件使用YUI Compressor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对包含PHP代码的JavaScript文件使用YUI Compressor,例如:

I want to use the YUI Compressor on JavaScript files that contain PHP code like for example:

<?php $include 'headerDefinitions.js.php'; ?>
function hello(name) {
    alert('Hello ' + name);
}
hello('<?= $_GET["name"] ?>');

这样显然在通过yui压缩程序运行时会引发一些错误,例如:

This obviously throws some errors when running through yui compressor like this:

java -jar yui-compressor.jar --type js -o target-file.js.php source-file.js.php

因为压缩器假定甚至PHP部分是JavaScript。有没有办法压缩JavaScript,同时保留和忽略PHP部分?所以上面的例子导致:

because the compressor assumes even the PHP part is JavaScript. Is there a way to compress the JavaScript while preserving and ignoring the PHP parts? So that the example above results in:

<?php $include 'headerDefinitions.js.php'; ?>function hello(a){alert('Hello '+a)}hello('<?= $_GET["name"] ?>');


推荐答案

回答自己:

jiggys回答单独的JavaScript从PHP可能是最干净的一个,应该遵循尽可能。但有时这是不可能的。在我的情况下,我不能划分PHP和JavaScript,而不花大量的时间(这是一个旧的和大项目)。

jiggys answer to separate JavaScript from PHP is probably the most clean one and should be followed when possible. But sometimes it's not possible. In my case I can't divide PHP and JavaScript without spending a huge amount of time (it's an old and big project).

无论如何,YUI Compressor不剥离以 / *!开头的JavaScript注释,因此关键是在注释块中包含PHP代码,如下所示:

Anyway, the YUI Compressor is not stripping JavaScript comments that start with /*! so the key is to surround PHP code in a comment block like this:

/*!
 <?php $include 'headerDefinitions.js.php'; ?> */
function hello(name) {
    alert('Hello ' + name);
}
hello('<?= $_GET["name"] ?>');

在JavaScript字符串中的PHP代码不需要进一步关注,因为它可以被忽略或填充一些版权信息。它们(显然)在压缩过程中保持不变:

PHP code within JavaScript strings need no further attention as they (obviously) remain untouched during the compressing process:

var myString = '<?= $_GET["name"] ?>';

不需要修改。您只需注意不要对JavaScript字符串声明和PHP代码中的字符串使用单引号或双引号。

does not need to be modified. You only have to take care not to use single or double quotes for both the JavaScript string declaration and strings in the PHP code.

这篇关于对包含PHP的JavaScript文件使用YUI Compressor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆