const fs = require('fs');
const path = require('path');
const gulp = require('gulp');
const uglify = require('gulp-uglify');
const cleanCss = require('gulp-clean-css');
const clean = require('gulp-clean');
const javascriptObfuscator = require('gulp-javascript-obfuscator');
const htmlmin = require('gulp-htmlmin');
// 查询batjs文件下所有目录
function findFiles(dir, files=[]) {
let entries = fs.readdirSync(dir, { withFileTypes: true });
for(let entry of entries) {
const fullPath = path.join(dir, entry.name);
if(entry.isDirectory()) {
folderPath.push(`./${fullPath}/*.js`)
findFiles(fullPath, files);
} else {
files.push(`./${fullPath}`);
}
}
return files;
}
// 根目录路径
const folderPath = ['./batjs/*.js'];
// 根目录
const directoryPath = './batjs/';
findFiles(directoryPath);
// 删除文件夹
gulp.task('clean', function () {
return gulp
// read:是否读取文件,true 读取, false 不读取,加快程序
// allowEmpty:允许文件夹为空或不存在,要不然会报错
.src('./dist/', { read: false, allowEmpty: true })
.pipe(clean());
})
// 合并压缩js
gulp.task('uglify', function() {
return gulp.src(['./**/*.js', '!./node_modules/**', '!./gulpfile.js']) // 匹配要压缩的JavaScript文件
.pipe(uglify()) // 使用UglifyJS进行压缩
.pipe(javascriptObfuscator({
compact: true,
controlFlowFlattening: false,
deadCodeInjection: false,
debugProtection: false,
disableConsoleOutput: true,
identifierNamesGenerator: 'hexadecimal',
rotateStringArray: true,
selfDefending: true,
shuffleStringArray: true,
splitStrings: false,
stringArray: true,
stringArrayThreshold: 0.75,
target: 'node',
}))
.pipe(gulp.dest('dist/js'));
});
// css压缩
gulp.task('minify-css', function() {
return gulp.src('./**/*.css') // 匹配要压缩的CSS文件
.pipe(cleanCss()) // 使用Clean CSS进行压缩
.pipe(gulp.dest('dist/css')); // 将压缩后的文件输出到目标目录
});
// html压缩
gulp.task('minify-html', () =>{
return gulp.src('./**/*.html')
.pipe(htmlmin({
removeComments: true, //清除HTML注释
collapseWhitespace: true, //压缩HTML
collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
minifyJS: true, //压缩页面JS
minifyCSS: true //压缩页面CSS
}))
.pipe(gulp.dest('dist/html'))
});
gulp.task('default', gulp.series('clean', 'uglify', 'minify-css', 'minify-html'));
如果找不到gulp,那么在管理员权限下下载gulp即可(前提是环境变量是对的)
还有需要注意的一点是,以上文件名必须是gulpfile.js,如:gulp uglify