gulpfile.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const gulp = require("gulp"),
  2. htmlmin = require("gulp-htmlmin"),
  3. minifyCss = require("gulp-minify-css"),
  4. sass = require("gulp-sass"),
  5. uglify = require("gulp-uglify"),
  6. babel = require("gulp-babel"),
  7. connect = require("gulp-connect"),
  8. del = require('del'),
  9. {
  10. createProxyMiddleware
  11. } = require('http-proxy-middleware');
  12. gulp.task("html", function (cb) {
  13. gulp.src("src/*.html")
  14. .pipe(htmlmin({
  15. removeComments: true, //清除HTML注释
  16. collapseWhitespace: true, //压缩HTML
  17. collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input checked />
  18. removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
  19. removeScriptTypeAttributes: false, //删除<script>的type="text/javascript"
  20. removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
  21. minifyJS: true, //压缩页面JS
  22. minifyCSS: true //压缩页面CSS
  23. }))
  24. .pipe(gulp.dest("dist"))
  25. .pipe(connect.reload());
  26. cb();
  27. })
  28. gulp.task("clean", function (cb) {
  29. del.sync(['dist']);
  30. cb();
  31. })
  32. gulp.task("css", function (cb) {
  33. gulp.src("src/css/*.scss")
  34. .pipe(sass())
  35. .pipe(minifyCss())
  36. .pipe(gulp.dest("dist/css"))
  37. .pipe(connect.reload());
  38. cb();
  39. })
  40. gulp.task("js", function (cb) {
  41. gulp.src("src/js/*.js")
  42. .pipe(babel({
  43. presets: ['@babel/env']
  44. }))
  45. .pipe(uglify())
  46. .pipe(gulp.dest("dist/js"))
  47. .pipe(connect.reload());
  48. cb();
  49. })
  50. gulp.task("lib", function (cb) {
  51. gulp.src("src/libs/*")
  52. .pipe(gulp.dest("dist/libs"))
  53. .pipe(connect.reload());
  54. cb();
  55. })
  56. gulp.task("img", function (cb) {
  57. gulp.src("src/img/**/*")
  58. .pipe(gulp.dest("dist/img"))
  59. .pipe(connect.reload());
  60. cb();
  61. })
  62. gulp.task('connect', function (cb) {
  63. connect.server({
  64. root: 'dist',
  65. port: 8080,
  66. livereload: true,
  67. middleware: function (connect, opt) {
  68. return [
  69. createProxyMiddleware('/api', {
  70. target: 'http://wodeshebao.com/', //代理的目标地址 120.79.211.173
  71. changeOrigin: true, //
  72. pathRewrite: { //路径重写规则
  73. '^/api': ''
  74. }
  75. })
  76. ]
  77. }
  78. });
  79. cb();
  80. });
  81. // 监听文件的改变,然后自动执行对应的任务
  82. gulp.task("watch", function (cb) {
  83. // 监听所有html文件的改变,然后执行html任务
  84. gulp.watch("src/**/*.html", gulp.series('html'));
  85. gulp.watch("src/js/**/*.js", gulp.series('js'));
  86. gulp.watch("src/css/**/*.scss", gulp.series('css'));
  87. cb();
  88. })
  89. gulp.task("init", gulp.series("clean", gulp.parallel("html", "js", "css", "lib", "img")))
  90. gulp.task("default", gulp.series("init", "connect", "watch"));