Minify JS files embedded with PHP code

守給你的承諾、 提交于 2019-12-12 03:56:35

问题


After long search in Google and on several Github repositories, I couldn't find anything solid (I found for HTML, not for JS)

The minifiers I use for JS files mess with my PHP code, for example, if I have the file example.js.php

<?php header("Content-Type: application/javascript");
$var1 = $_GET['f'];
?>

//some JS and PHP code

For example, the JS minifiers I use, convert $_GET['f'] to $_GET.f; which is OK for a JS object, but not for PHP.

Any ideas on how to compact the JS code leaving the PHP intact?


回答1:


More up to date than the answers in the duplicate question. You could use JShrink

You could create your javascript and store it all in a single string, then pass this string into the library like in the example on the JSrink page.




回答2:


Minifiers are trying to make nearly impossible decisions, and embedding them in PHP is really stretching the friendship.

You should minify the JavaScript separately, and then included it or send it through the PHP.

Two possibilities are:

<?php
    header('Content-Type: application/javascript');
    require_once 'script.min.js';
?>

if that is appropriate, or

<?php
    header('Content-Type: application/javascript');
    print file_get_contents('script.min.js');
?>

depending on why you’re trying to mix them.



来源:https://stackoverflow.com/questions/42974256/minify-js-files-embedded-with-php-code

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