如何在PHP中轻松缩小JS…或者其他什么
我四处看了看,但还是有点困惑 我尝试了Crockford的JSMin,但是WinXP由于某种原因无法解压缩可执行文件 但我真正想要的是一个简单易用的JS迷你程序,它使用PHP缩小JS代码并返回结果 原因是: 我有两个文件(例如)在其中工作:scripts.js和scripts\u template.js scripts_模板是我编写的普通代码——然后我必须缩小它并将缩小后的脚本粘贴到scripts.js中——我在网站上实际使用的脚本 我想通过在我的页面上做这样的事情来根除中间人:如何在PHP中轻松缩小JS…或者其他什么,php,javascript,minify,Php,Javascript,Minify,我四处看了看,但还是有点困惑 我尝试了Crockford的JSMin,但是WinXP由于某种原因无法解压缩可执行文件 但我真正想要的是一个简单易用的JS迷你程序,它使用PHP缩小JS代码并返回结果 原因是: 我有两个文件(例如)在其中工作:scripts.js和scripts\u template.js scripts_模板是我编写的普通代码——然后我必须缩小它并将缩小后的脚本粘贴到scripts.js中——我在网站上实际使用的脚本 我想通过在我的页面上做这样的事情来根除中间人: <scr
<script type="text/javascript" src="scripts.php"></script>
然后对于scripts.php的内容:
<?php include("include.inc"); header("Content-type:text/javascript"); echo(minify_js(file_get_contents("scripts_template.js")));
我已经用了相当长一段时间了。连接文件时可能有点危险,因为闭包末尾可能缺少分号
缓存缩小的输出并回显缓存的内容是一个明智的想法,只要它比源文件更新
require 'jsmin.php';
if(filemtime('scripts_template.js') < filemtime('scripts_template.min.js')) {
read_file('scripts_template.min.js');
} else {
$output = JSMin::minify(file_get_contents('scripts_template.js'));
file_put_contents('scripts_template.min.js', $output);
echo $output;
}
需要'jsmin.php';
如果(filemtime('scripts_template.js')
你也可以试试。我以前从未使用过它,因为我以前在JSMin方面没有遇到过困难,但是下面的代码应该可以做到这一点。我没有意识到这一点,但JShrink需要PHP5.3和名称空间
require 'JShrink/Minifier.php';
if(filemtime('scripts_template.js') < filemtime('scripts_template.min.js')) {
read_file('scripts_template.min.js');
} else {
$output = \JShrink\Minifier::minify(file_get_contents('scripts_template.js'));
file_put_contents('scripts_template.min.js', $output);
echo $output;
}
需要'JShrink/Minifier.php';
如果(filemtime('scripts_template.js')
看看Assetic,它是PHP中一个很棒的资产管理库。它与Symfony2集成良好,应用广泛
根据服务器的限制(例如,不在运行),也许您还可以在PHP之外寻找一个迷你程序,并使用shell\u exec()
运行它。例如,如果您可以在服务器上运行Java,请在服务器上放置的副本并直接使用它
然后scripts.php将类似于:
<?php
$cmd = "java -cp [path-to-yui-dir] -jar [path-to-yuicompressor.jar] [path-to-scripts_template.js]";
echo(shell_exec($cmd));
?>
其他建议:在部署到服务器之前,将缩小步骤构建到开发工作流中。例如,我将EclipsePHP项目设置为将JS和CSS文件压缩到“build”文件夹中。工作起来像个符咒。使用“PHPWee”:
(它也使用了JSmin
),我把@robertk解决方案推得更远了一点
此解决方案允许缩小CSS和JS文件。如果找不到未缩小的文件,它将返回空字符串。如果缩小的文件比未缩小的文件旧,它将尝试创建它。如果缩小的文件不存在,它将为其创建一个子文件夹。如果该方法可以成功缩小文件,它将以
(javascript)或
(CSS)标记的形式返回该文件。否则,该方法将在适当的标记中返回非精简版本
注意:使用PHP7.0.13进行测试
/**
* Try to minify the JS/CSS file. If we are not able to minify,
* returns the path of the full file (if it exists).
*
* @param $matches Array
* 0 = Full partial path
* 1 = Path without the file
* 2 = File name and extension
*
* @param $fileType Boolean
* FALSE: css file.
* TRUE: js file
*
* @return String
*/
private static function createMinifiedFile(array $matches, bool $fileType)
{
if (strpos($matches[1], 'shared_code') !== false) {
$path = realpath(dirname(__FILE__)) . str_replace(
'shared_code',
'..',
$matches[1]
);
} else {
$path = realpath(dirname(__FILE__)) .
"/../../" . $matches[1];
}
if (is_file($path . $matches[2])) {
$filePath = $link = $matches[0];
$min = 'min/' . str_replace(
'.',
'.min.',
$matches[2]
);
if (!is_file($path . $min) or
filemtime($path . $matches[2]) >
filemtime($path . $min)
) {
if (!is_dir($path . 'min')) {
mkdir($path . 'min');
}
if ($fileType) { // JS
$minified = preg_replace(
array(
'/(\))\R({)/',
'/(})\R/'
),
array(
'$1$2',
'$1'
),
Minify::js(
(string) file_get_contents(
$path . $matches[2]
)
)
);
} else { // CSS
$minified = preg_replace(
'@/\*(?:[\r\s\S](?!\*/))+\R?\*/@', //deal with multiline comments
'',
Minify::css(
(string) file_get_contents(
$path . $matches[2]
)
)
);
}
if (!empty($minified) and file_put_contents(
$path . $min,
$minified
)
) {
$filePath = $matches[1] . $min;
}
} else { // up-to-date
$filePath = $matches[1] . $min;
}
} else { // full file doesn't exists
$filePath = "";
}
return $filePath;
}
/**
* Return the minified version of a CSS file (must end with the .css extension).
* If the minified version of the file is older than the full CSS file,
* the CSS file will be shrunk.
*
* Note: An empty string will be return if the CSS file doesn't exist.
*
* Note 2: If the file exists, but the minified file cannot be created,
* we will return the path of the full file.
*
* @link https://github.com/searchturbine/phpwee-php-minifier Source
*
* @param $path String name or full path to reach the CSS file.
* If only the file name is specified, we assume that you refer to the shared path.
*
* @return String
*/
public static function getCSSMin(String $path)
{
$link = "";
$matches = array();
if (preg_match(
'@^(/[\w-]+/view/css/)?([\w-]+\.css)$@',
$path,
$matches
)
) {
if (empty($matches[1])) { // use the default path
$matches[1] = self::getCssPath();
$matches[0] = $matches[1] . $matches[2];
}
$link = self::createMinifiedFile($matches, false);
} else {
$link = "";
}
return (empty($link) ?
'' :
'<link rel="stylesheet" href="' . $link . '">'
);
}
/**
* Return the path to fetch CSS sheets.
*
* @return String
*/
public static function getCssPath()
{
return '/shared_code/css/' . self::getCurrentCSS() . "/";
}
/**
* Return the minified version of a JS file (must end with the .css extension).
* If the minified version of the file is older than the full JS file,
* the JS file will be shrunk.
*
* Note: An empty string will be return if the JS file doesn't exist.
*
* Note 2: If the file exists, but the minified file cannot be created,
* we will return the path of the full file.
*
* @link https://github.com/searchturbine/phpwee-php-minifier Source
*
* @param $path String name or full path to reach the js file.
*
* @return String
*/
public static function getJSMin(String $path)
{
$matches = array();
if (preg_match(
'@^(/[\w-]+(?:/view)?/js/)([\w-]+\.js)$@',
$path,
$matches
)
) {
$script = self::createMinifiedFile($matches, true);
} else {
$script = "";
}
return (empty($script) ?
'' :
'<script src="' . $script . '"></script>'
);
}
/**
*尝试缩小JS/CSS文件。如果我们不能缩小,
*返回完整文件的路径(如果存在)。
*
*@param$匹配数组
*0=完整部分路径
*1=没有文件的路径
*2=文件名和扩展名
*
*@param$fileType布尔值
*错误:css文件。
*TRUE:js文件
*
*@返回字符串
*/
私有静态函数createMinifiedFile(数组$matches,bool$fileType)
{
if(strpos($matches[1],'shared_code')!==false){
$path=realpath(dirname(_文件__)).str\u replace(
“共享_代码”,
'..',
$matches[1]
);
}否则{
$path=realpath(dirname(_文件__))。
“/../../”$matches[1];
}
如果(是_文件($path.$matches[2])){
$filePath=$link=$matches[0];
$min='min/'。str_替换(
'.',
"民先生",,
$matches[2]
);
如果(!is_file($path.$min)或
filemtime($path.$matches[2])>
filemtime($path.$min)
) {
如果(!is_dir($path.'min')){
mkdir($path.min');
}
如果($fileType){//JS
$minified=预更换(
排列(
“/(\)\R({)/”,
“/(})\R/”
),
排列(
'$1$2',
'$1'
),
缩小::js(
(字符串)文件\u获取\u内容(
$path.$matches[2]
)
)
);
}else{//CSS
$minified=预更换(
'@/\*(?:[\r\s\s](?!\*/)+\r?\*/@',//处理多行注释
'',
缩小::css(
(字符串)文件\u获取\u内容(
$path.$matches[2]
)
)
);
}
如果(!empty($minified)和文件内容(
$path.$min,
$minified
)
) {
$filePath=$matches[1]。$min;
}
}else{//最新
$filePath=$matches[1]。$min;
}
}否则{//完整文件不存在
$filePath=“”;
}
返回$filePath;
}
/**
*返回CSS文件的缩小版本(必须以.CSS扩展名结尾)。
*如果文件的缩小版本早于完整CSS文件,
*CSS文件将被收缩。
*
*注意:将返回一个空字符串
{$PageController->getCSSMin("main_frame.css")}
//Output: <link rel="stylesheet" href="/shared_code/css/default/min/main_frame.min.css">
{$PageController->getCSSMin("/gem-mechanic/view/css/gem_mechanic.css")}
//Output: <link rel="stylesheet" href="/gem-mechanic/view/css/min/gem_mechanic.min.css">
{$PageController->getJSMin("/shared_code/js/control_utilities.js")}
//Output: <script src="/shared_code/js/min/control_utilities.min.js"></script>
{$PageController->getJSMin("/PC_administration_interface/view/js/error_log.js")}
//Output: <script src="/PC_administration_interface/view/js/min/error_log.min.js"></script>
/**
* Test that we can minify CSS files successfully.
*/
public function testGetCSSMin()
{
//invalid style
$this->assertEmpty(
PageController::getCSSMin('doh!!!')
);
//shared style
$path = realpath(dirname(__FILE__)) . '/../css/default/min/main_frame.min.css';
if (is_file($path)) {
unlink ($path);
}
$link = PageController::getCSSMin("main_frame.css");
$this->assertNotEmpty($link);
$this->assertEquals(
'<link rel="stylesheet" href="/shared_code/css/default/min/main_frame.min.css">',
$link
);
$this->validateMinifiedFile($path);
//project style
$path = realpath(dirname(__FILE__)) . '/../../gem-mechanic/view/css/min/gem_mechanic.min.css';
if (is_file($path)) {
unlink ($path);
}
$link = PageController::getCSSMin("/gem-mechanic/view/css/gem_mechanic.css");
$this->assertNotEmpty($link);
$this->assertEquals(
'<link rel="stylesheet" href="/gem-mechanic/view/css/min/gem_mechanic.min.css">',
$link
);
$this->validateMinifiedFile($path);
}
/**
* Test that we can minify JS files successfully.
*/
public function testGetJSMin()
{
//invalid script
$this->assertEmpty(
PageController::getJSMin('doh!!!')
);
//shared script
$path = realpath(dirname(__FILE__)) . '/../js/min/control_utilities.min.js';
if (is_file($path)) {
unlink ($path);
}
$script = PageController::getJSMin("/shared_code/js/control_utilities.js");
$this->assertNotEmpty($script);
$this->assertEquals(
'<script src="/shared_code/js/min/control_utilities.min.js"></script>',
$script
);
$this->validateMinifiedFile($path);
//project script
$path = realpath(dirname(__FILE__)) . '/../../PC_administration_interface/view/js/min/error_log.min.js';
if (is_file($path)) {
unlink ($path);
}
$script = PageController::getJSMin("/PC_administration_interface/view/js/error_log.js");
$this->assertNotEmpty($script);
$this->assertEquals(
'<script src="/PC_administration_interface/view/js/min/error_log.min.js"></script>',
$script
);
$this->validateMinifiedFile($path);
}
/**
* Make sure that the minified file exists and that its content is valid.
*
* @param $path String the path to reach the file
*/
private function validateMinifiedFile(string $path)
{
$this->assertFileExists($path);
$content = (string) file_get_contents($path);
$this->assertNotEmpty($content);
$this->assertNotContains('/*', $content);
$this->assertEquals(
0,
preg_match(
'/\R/',
$content
)
);
}