Using the YUI Compressor on JavaScript files containing PHP

耗尽温柔 提交于 2019-12-11 06:25:46

问题


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"] ?>');

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

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"] ?>');

回答1:


It won't work. You should define all of your functions in plain .js files and then any dynamic values or function calls be on your PHP page. Aside from allowing compression, it will allow your .js files to be cached properly by the browser.




回答2:


To answer myself:

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).

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"] ?>');

That's all. There will be an empty comment block when viewed in the browser, but it can be neglected or filled with some copyright info.

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

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

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.



来源:https://stackoverflow.com/questions/6307124/using-the-yui-compressor-on-javascript-files-containing-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!