chaihongjun.me

单页面的Grunt工具使用总结

虽然Grunt已经没有Gulp流行了,但是小规模的应用还是可以的。这里有一份自用的Grunt插件组合及配置清单。可以快速的实现页面的优化,优化的内容有:

  1. 清理无效的图片文件

  2. 清理无用的CSS代码

  3. 压缩CSS,JS

  4. 压缩图片文件

  5. 压缩HTML文件

  6. 给CSS和JS引用路径添加时间戳

使用前提:

  1. 单页面(竞价专题)

  2. 只有一个CSS文件(如果有多个请提前合并)/只有一个JS文件(如果有多个请提前合并)

  3. 图片目录images

  //   1. 原始html,CSS,JS和图片分别在html,css,js,img目录内
  //   2. 如果有多个JS/CSS,则合并之后仍然分别在JS,CSS目录
  //   3. 如果只有单一JS/CSS,则分别压缩之后在opt_js,opt_css目录里
  //   4.优化后的图片在opt_img里面
  //   5.压缩后的html文件在opt_html里面
  module.exports = function(grunt) {
      'use strict';
      require('time-grunt')(grunt);
      grunt.initConfig({
          /************     清理无用的项目文件     ************/
          unused: {
              options: {
                  reference: 'dist/img/',
                  directory: ['dist/*.html'],
                  days: 30,
                  remove: false, // set to true to delete unused files from project
                  reportOutput: 'report.txt', // set to false to disable file output
                  fail: false // set to true to make the task fail when unused files are found
              }
          },
          /************       CSS文件处理     ************/
          /****    清理无用 CSS    ****/
          uncss: {
              dist: {
                  files: {
                      'dist/css/all.css': ['dist/*.html']
                  }
              },
              options: {
                  report: 'gzip'
              }
          },
          /****     压缩 CSS    ****/
          cssmin: {
              options: {
                  report: 'gzip',
                  keepSpecialComments: 0 /* 移除 CSS 文件中的所有注释 */
              },
              minify: {
                  expand: true,
                  cwd: 'dist/css/',
                  src: ['*.css'],
                  dest: 'dist/css/',
                  ext: '.css'
              }
          },
          /************       CSS文件处理     ************/
          /************       JS文件处理     ************/
          /****        最小化、混淆、合并 JavaScript 文件       ****/
          uglify: {
              target: {
                  files: {
                      'dist/js/all.js': ['dist/js/*.js'] //合并成all.js
                  }
              },
              //最小化、混淆所有 js/ 目录下的 JavaScript 文件
              minjs: {
                  files: [{
                      expand: true,
                      cwd: 'dist/js/',
                      src: ['**/*.js', '!**/*.min.js'],
                      dest: 'dist/js/',
                      ext: '.js' //压缩成all.min.js
                  }]
              },
              options: {
                  mangle: false, //不混淆变量名
                  // preserveComments: 'all', //不删除注释,还可以为 false(删除全部注释),some(保留@preserve @license @cc_on等注释)
                  report: 'gzip'
              }
          },
          /************       图片文件处理     ************/
          /****        压缩优化图片大小        ****/
          imagemin: {
              dist: {
                  options: {
                      optimizationLevel: 7,
                      progressive: true,
                      interlaced: true,
                      pngquant: { quality: "65-80" }
                  },
                  files: [{
                      expand: true,
                      cwd: 'dist/',
                      src: ['img/**/*.{png,jpg,jpeg|gif|svg}', '[images/**/*.{png,jpg,jpeg|gif|svg}]'], // 优化 img 目录下所有 png/jpg/jpeg 图片
                      dest: ['dist/img', 'dist/images'],
                      //dest: 'dest/img/' // 优化后的图片保存位置,默认覆盖
                  }]
              }
          },
          /*  新的图片处理*/
          image: {
              static: {
                  options: {
                      pngquant: true,
                      optipng: false,
                      zopflipng: true,
                      jpegRecompress: false,
                      jpegoptim: true,
                      mozjpeg: true,
                      guetzli: false,
                      gifsicle: true,
                      svgo: true
                  },
                  // files: {
                  //   'dist/img.png': 'src/img.png',
                  //   'dist/img.jpg': 'src/img.jpg',
                  //   'dist/img.gif': 'src/img.gif',
                  //   'dist/img.svg': 'src/img.svg'
                  // }
              },
              dynamic: {
                  files: [{
                      expand: true,
                      cwd: 'dist/img/',
                      src: ['**/*.{png,jpg,gif,svg}'],
                      dest: 'dest/img/'
                  }]
              }
          },
          cachebust: {
              custom_options: {
                  options: {
                      type: 'timestamp'
                  },
                  files: [{
                      expand: true,
                      cwd: 'dist',
                      src: [
                          '*.html'
                      ],
                      dest: 'dist/'
                  }]
              }
          },
          /************       图片文件处理     ************/
          /************     HTML 文件处理     ************/
          //压缩HTML
          htmlmin: {
              options: {
                  /* 忽略dedecms {dede: ...} [field:.../]  {/dede:..} <? ... ?>  标签*/
                  ignoreCustomFragments: [/{dede:[\s\S]*?}/, /\[field:[\s\S]*?\/]/, /{\/dede:[\s\S]*?}/, /<\?[\s\S]*?\?>/],
                  ignoreCustomComments: [/<!--[\s]{dede:[\s\S]*?}[\s]-->/],
                  /* 删除 type="text/javascript"  */
                  removeScriptTypeAttributes: true,
                  /* 删除 type="text/css" */
                  removeStyleLinkTypeAttributes: true,
                  /*删除注释*/
                  removeComments: false,
                  /* 删除 script 和style标签内的HTML注释*/
                  removeCommentsFromCDATA: true,
                  /*压缩空白*/
                  collapseWhitespace: true,
                  /*压缩布尔属性*/
                  collapseBooleanAttributes: true,
                  /*删除属性引号*/
                  removeAttributeQuotes: false,
                  /*删除冗余属性*/
                  removeRedundantAttributes: true,
                  /*使用短文档类型声明*/
                  useShortDoctype: true,
                  /*删除空属性*/
                  removeEmptyAttributes: true,
                  /*删除空元素*/
                  removeEmptyElements: false,
                  /*删除可选标签*/
                  removeOptionalTags: false,
                  /*保持反斜杠*/
                  keepClosingSlash: true,
                  /*  */
                  includeAutoGeneratedTags: true,
                  /* display:inline 属性不间隙 */
                  collapseInlineTagWhitespace: false,
                  html5: true,
                  report: 'gzip'
              },
              html: {
                  files: [{
                      expand: true,
                      cwd: 'dist/',
                      src: ['**/*.htm', '**/*.html'],
                      dest: 'dist/'
                  }]
              }
          },
      });
      /************     加载frunt模块     ************/
      grunt.loadNpmTasks('grunt-unused'); //清理无效的文件(图片)
      grunt.loadNpmTasks('grunt-uncss'); //清理无效的CSS文件选择器
      grunt.loadNpmTasks('grunt-contrib-cssmin'); //压缩CSS
      grunt.loadNpmTasks('grunt-contrib-uglify'); //合并压缩JS
      grunt.loadNpmTasks('grunt-contrib-imagemin'); //图片压缩优化
      grunt.loadNpmTasks('grunt-image');
      grunt.loadNpmTasks('grunt-contrib-htmlmin'); //HTML文件压缩优化
      grunt.loadNpmTasks('grunt-cachebust');
      /************     加载frunt模块     ************/
      /************    注册frunt 任务    ************/
      grunt.registerTask('comimage', ['imagemin']);
      grunt.registerTask('yasuoimage', ['image']);
      grunt.registerTask('assets', ['cachebust']);
      /*
         1.清理未使用的图片文件(img目录) dist/img
         2.清理CSS文件 => dist/css/all.css
         3.压缩CSS文件 => dist/css/all.min.css
         4.合并压缩JS文件  => dist/js/all.min.js
         5.图片压缩=> dist/img,dist/images
         6.HTML文件压缩 => dist/
         7.CSS,JS文件增加时间戳  dist/
         */
      grunt.registerTask('all', ['unused', 'uncss', 'cssmin', 'uglify', 'imagemin','htmlmin','cachebust']);

  };

注解:

  1. dist目录是单页根目录,下面的css,js,img,images分别存放静态文件

  2. grunt工具的临时文件也在其中,最后产生的文件也在其中

  3. 需要安装的插件可以通过配置文件底部加载的任务了解到

知识共享许可协议本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。作者:chaihongjun»