之前讲过从零开始部署一个 Laravel 项目
这次讲一下怎么自动压缩php模板文件
安装依赖
cd /var/www/html/laravel-project
npm i -D laravel-mix@^5.x laravel-mix-template-minifier watch shelljs
压缩处理
打开文件webpack.mix.js,并添加以下内容:
mix.minTemplate \= require("laravel-mix-template-minifier");
mix.minTemplate("storage/framework/views/\*.php", "storage/framework/views/", {
collapseInlineTagWhitespace: true,
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true,
processConditionalComments: true,
removeAttributeQuotes: false,
removeComments: true,
removeTagWhitespace: false,
trimCustomFragments: false,
});
监听文件变化
在项目根目录新建文件compress.js,写入以下内容:
let shell = require("shelljs");
let watch = require("watch");
let precessing = false;
watch.watchTree("./storage/framework/views", function(f, curr, prev) {
if (!precessing) {
precessing = true;
shell.exec("npm run prod");
setTimeout(() => {
precessing = false;
}, 5000);
}
});
开机自启监听命令
以上步骤完成后,在命令行执行node compress.js,即可实现自动监听压损模板文件,可以打开网页看到页面内的
有些页面的js代码不会压缩,暂时没找到什么原因。
由于监听文件命令是常驻命令台的,所以我们要设置开机自启,并且后台启动该命令。
nano /etc/rc.d/rc.local
# 添加以下内容
cd /var/www/html/ysmj-laravel
nohup node compress.js > /var/www/html/laravel-project/compress.out 2>&1 &
# 保存文件。然后设置权限使其开机自启
chmod +x /etc/rc.d/rc.local
优化
由于laravel自带的package命令npm run prod中带有--progress,长期使用,会导致压缩日志compress.out日益过大。
在package.json中,新添加compress命令,去除--progress参数,如下:
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"compress": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
然后compress.js文件需要修改,如下:
let shell = require("shelljs");
let watch = require("watch");
let precessing = false;
watch.watchTree("./storage/framework/views", function(f, curr, prev) {
if (!precessing) {
precessing = true;
shell.exec("npm run compress");
setTimeout(() => {
precessing = false;
}, 5000);
}
});