chaihongjun.me

grunt简洁使用版(合并压缩)

grunt简洁使用版(合并压缩)

    grunt是一套前端自动化工具,一个基于nodeJs的命令行工具,一般用于下面几个场景:

  1.             压缩页面文件(js,css,html,jpg,png)

  2.             合并页面文件(js,css,html)

  3.             语法检查(js,css)

    an so on.grunt基于NODEJS,所以先安装NODEJS,Grunt通过npm管理安装,npm已经默认和nodejs一起安装了,在nodejs安装过程的“下一步”中可以看到,所以无需单独再安装npm。

     

    一.从官网(nodejs)下载

    二.安装nodejs(双击)

    三.选择一个项目目录,比如:F:\Nodejs\在该目录下安装grunt,特别提示,从这一步开始安装过程全部在命令行内进行。

grunt简洁使用版(合并压缩)

npm install grunt-cli -g --save-dev

    上面命令是标准的安装命令,只安装grunt-cli即可,-g参数表全局,整条命令可以度娘或者谷歌,接着依次下载安装优化插件(无先后顺序,按情况)

npm install grunt-contrib-htmlmin --save-dev
npm install grunt-contrib-csslint --save-dev
npm install grunt-contrib-jshint --save-dev
npm install grunt-contrib-cssmin --save-dev
npm install grunt-contrib-imagemin --save-dev
npm install grunt-contrib-concat --save-dev
npm install grunt-contrib-uglify --save-dev
npm install grunt-contrib-watch --save-dev

    然后

npm init

    该命令初始化npm包管理

    然后再手动编辑项目管理文件Gruntfile.js

module.exports = function(grunt) {
    'use strict';
    grunt.initConfig({
        csslint: {
            /* 检查 CSS 语法 */
            src: ['css/*.css']
        },
        jshint: {
            /* 检查 js 语法 */
            all: ['Gruntfile.js', 'js/*.js']
        },
        imagemin: {
            /* 压缩优化图片大小 */
            dist: {
                options: {
                    optimizationLevel: 3
                },
                files: [{
                    expand: true,
                    cwd: 'img/',
                    src: ['**/*.{png,jpg,jpeg}'], // 优化 img 目录下所有 png/jpg/jpeg 图片
                    dest: 'opt_img/' // 优化后的图片保存位置,默认覆盖
                }]
            }
        },
        concat: {
            /* 合并 CSS 文件 */
            css: {
                // src: ['css/*.css' ],
                src: ['css/**/*.css'],
                /* 根据目录下文件情况配置 */
                dest: 'opt_css/all.css'
            },
            js: {
                src: ['js/**/*.js'],
                /* 根据目录下文件情况配置 如果可以使用 require.js/LABjs 等配置更佳 */
                dest: 'opt_js/all.js'
            }
        },
        cssmin: {
            /*压缩 CSS 文件为 .min.css */
            options: {
                report: 'gzip',
                keepSpecialComments: 0 /* 移除 CSS 文件中的所有注释 */
            },
            minify: {
                expand: true,
                cwd: 'opt_css/',
                src: ['*.css'],
                dest: 'opt_css/',
                ext: '.min.css'
            }
        },
        uglify: {
            /* 最小化、混淆、合并 JavaScript 文件 */
            target: {
                files: {
                    'js/all.min.js': ['js/*.js']
                }
            },
            minjs: { //最小化、混淆所有 js/ 目录下的 JavaScript 文件
                files: [{
                    expand: true,
                    cwd: 'opt_js/',
                    src: ['**/*.js', '!**/*.min.js'],
                    dest: 'opt_js/',
                    ext: '.min.js'
                }]
            }
        },
        //压缩HTML
        htmlmin: {
            options: {
                removeComments: true,
                removeCommentsFromCDATA: true,
                collapseWhitespace: true,
                collapseBooleanAttributes: true,
                removeAttributeQuotes: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeEmptyElements: true,
                removeOptionalTags: true,
                removeStyleLinkTypeAttributes: true,
                removeScriptTypeAttributes: true,
                keepClosingSlash: true
            },
            html: {
                files: [{
                    expand: true,
                    cwd: 'html/',
                    src: ['**/*.html'],
                    dest: 'opt_html/'
                }]
            }
        },
        watch: {
            /* 监控文件变化并执行相应任务 */
            img: {
                files: ['img/*.{png,jpg,jpeg}'],
                options: {
                    livereload: true
                }
            },
            css: {
                options: {
                    event: ['changed', 'added'],
                    livereload: true
                },
                files: ['css/*.css']
            },
            js: {
                options: {
                    livereload: true
                },
                files: ['js/*.js']
            },
            html: {
                options: {
                    livereload: true
                },
                files: ['html/*.html']
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-htmlmin');
    grunt.loadNpmTasks('grunt-contrib-csslint');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-imagemin');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    // 定义默认任务
    //grunt.registerTask('css_c', ['cssmin','concat:css']);
    grunt.registerTask('image', ['imagemin']);
    grunt.registerTask('html', ['htmlmin']);
    grunt.registerTask('js', ['concat:js', 'uglify:minjs']);
    grunt.registerTask('default', ['csslint', 'jshint', 'imagemin', 'cssmin', 'concat', 'uglify']);
    grunt.registerTask('css', ['concat:css', 'cssmin']);
    grunt.registerTask('dev', ['csslint', 'jshint']);
    grunt.registerTask('dest', ['imagemin', 'concat:css', 'cssmin', 'uglify:minjs']);
};
//注解:
//cwd: '', 指向的目录是相对的,全称Change Working Directory更改工作目录
//src: ['**'], 指向源文件,**是一个通配符,用来匹配Grunt任何文件
//dest: 'images', 用来输出结果任务
//expand: true expand参数为true来启用动态扩展,涉及到多个文件处理需要开启


    参考资料:

  1.             《Grunt配置文件编写技巧及示范

  2.             《JavaScript 项目构建工具 Grunt 实践:安装和创建项目框架

############################# UPDATE 2016-8-10 新版本增加 对sass的使用,uncss 暂时无法使用 #################

/*
* @Author: puffbaby
* @Date:   2016-08-09 16:43:06
* @Last Modified by:   puffbaby
* @Last Modified time: 2016-08-09 16:43:32
*/
	    //   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';
	        // var mozjpeg = require('imagemin-mozjpeg');
	        grunt.initConfig({

	            /************       CSS文件处理     ************/

	            /*****    检查 CSS 语法  ****/


	            csslint: {
	                src: ['css/*.css']
	            },

	            /****    清理无用 CSS    ****/
	            uncss: {
	                dist: {
	                    files: {
	                        'opt_css/tidy.css': ['html/index.html']
	                    }
	                },
	                options: {
	                    report: 'gzip'
	                }
	            },

	            /****     压缩 CSS    ****/
	            cssmin: {
	                options: {
	                    report: 'gzip',
	                    keepSpecialComments: 0 /* 移除 CSS 文件中的所有注释 */
	                },
	                minify: {
	                    expand: true,
	                    cwd: 'opt_css/',
	                    src: ['*.css'],
	                    dest: 'opt_css/',
	                    ext: '.min.css'
	                }
	            },
	            sass: {
	                dist: {
	                    files: [{
	                        expand: true,
	                        cwd: 'css/',
	                        src: ['*.scss'],
	                        dest: 'css/',
	                        ext: ['.css']
	                    }]
	                }
	            },
	            /************       CSS文件处理     ************/


	            /************       JS文件处理     ************/

	            /****      检查 js 语法    ****/
	            jshint: {
	                all: ['Gruntfile.js', 'js/*.js']
	            },

	            /****        最小化、混淆、合并 JavaScript 文件       ****/
	            uglify: {
	                target: {
	                    files: {
	                        'js/all_in_one.js': ['js/*.js']
	                    }
	                },
	                //最小化、混淆所有 js/ 目录下的 JavaScript 文件
	                minjs: {
	                    files: [{
	                        expand: true,
	                        cwd: 'js/',
	                        src: ['**/*.js', '!**/*.min.js'],
	                        dest: 'opt_js/',
	                        ext: '.min.js'
	                    }]
	                },
	                options: {
	                    mangle: false, //不混淆变量名
	                    // preserveComments: 'all', //不删除注释,还可以为 false(删除全部注释),some(保留@preserve @license @cc_on等注释)
	                    report: 'gzip'
	                }
	            },
	            /************       JS文件处理     ************/


	            /************       图片文件处理     ************/

	            /****        压缩优化图片大小        ****/
	            imagemin: {
	                dist: {
	                    options: {
	                        optimizationLevel: 7,
	                        progressive: true,
	                        interlaced: true,
	                        pngquant: { quality: "65-80" }
	                    },
	                    files: [{
	                        expand: true,
	                        cwd: 'img',
	                        src: ['**/*.{png,jpg,jpeg|gif|svg}'], // 优化 img 目录下所有 png/jpg/jpeg 图片
	                        dest: 'opt_img/' // 优化后的图片保存位置,默认覆盖
	                    }]
	                }
	            },
	            /************       图片文件处理     ************/

	            /************      CSS JS 文件处理     ************/

	            /****    合并 JS/CSS 文件    ****/
	            concat: {

	                /****    合并 CSS 文件    ****/
	                css: {
	                    // src: ['css/*.css' ],
	                    src: ['css/**/*.css'],
	                    /* 根据目录下文件情况配置 */
	                    dest: 'css/all_in_one.css'
	                },

	                /****    合并 JS 文件    ****/
	                js: {
	                    src: ['js/**/*.js'],
	                    /* 根据目录下文件情况配置 如果可以使用 require.js/LABjs 等配置更佳 */
	                    dest: 'js/all_in_one.js'
	                }
	            },
	            /****    合并 JS/CSS 文件    ****/
	            /************      CSS JS 文件处理     ************/


	            /************     HTML 文件处理     ************/

	            //压缩HTML
	            htmlmin: {
	                options: {
	                    removeComments: true,
	                    /*删除注释*/
	                    removeCommentsFromCDATA: true,
	                    /* 删除 script 和style标签内的HTML注释*/
	                    collapseWhitespace: true,
	                    /*压缩空白*/
	                    collapseBooleanAttributes: true,
	                    /*压缩布尔属性*/
	                    // removeAttributeQuotes: true,
	                    /*删除属性引号*/
	                    removeRedundantAttributes: true,
	                    /*删除冗余属性*/
	                    useShortDoctype: true,
	                    /*使用短文档类型声明*/
	                    removeEmptyAttributes: true,
	                    /*删除空属性*/
	                    // removeEmptyElements: true,
	                    /*删除空元素*/
	                    removeOptionalTags: true,
	                    /*删除可选标签*/
	                    removeStyleLinkTypeAttributes: true,
	                    /*删除样式链接类型属性*/
	                    removeScriptTypeAttributes: true,
	                    /*删除脚本类型属性*/
	                    keepClosingSlash: true,
	                    /*保持反斜杠*/
	                    report: 'gzip'
	                },
	                html: {
	                    files: [{
	                        expand: true,
	                        cwd: 'html/',
	                        src: ['**/*.html'],
	                        dest: 'opt_html/'
	                    }]
	                }
	            },

	            /************     HTML 文件处理     ************/


	            /************     监控文件变化     ************/
	            watch: {
	                /* 监控文件变化并执行相应任务 */
	                img: {
	                    files: ['img/*.{png,jpg,jpeg}'],
	                    options: {
	                        livereload: true
	                    }
	                },
	                css: {
	                    options: {
	                        event: ['changed', 'added'],
	                        livereload: true
	                    },
	                    files: ['css/*.css']
	                },
	                js: {
	                    options: {
	                        livereload: true
	                    },
	                    files: ['js/*.js']
	                },
	                html: {
	                    options: {
	                        livereload: true
	                    },
	                    files: ['html/*.html']
	                }
	            }
	        });
	        /************     监控文件变化     ************/


	        /************     加载frunt模块     ************/
	        grunt.loadNpmTasks('grunt-contrib-csslint');
	        grunt.loadNpmTasks('grunt-contrib-cssmin');
	        grunt.loadNpmTasks('grunt-contrib-sass');
	        grunt.loadNpmTasks('grunt-contrib-jshint');
	        grunt.loadNpmTasks('grunt-contrib-uglify');
	        grunt.loadNpmTasks('grunt-contrib-imagemin');
	        grunt.loadNpmTasks('grunt-contrib-htmlmin');
	        /************     加载frunt模块     ************/

	        /************    注册frunt 任务    ************/

	        grunt.loadNpmTasks('grunt-contrib-concat');

	        grunt.registerTask('check_gf', ['jshint']);
	        //grunt.loadNpmTasks('grunt-contrib-watch');
	        grunt.registerTask('default', ['csslint', 'cssmin', 'jshint', 'uglify:minjs', 'imagemin', 'htmlmin']);
	        grunt.registerTask('uncss', ['uncss']);
	        grunt.registerTask('css', ['cssmin', 'concat:css']);
	        grunt.registerTask('scss', ['sass']);
	        grunt.registerTask('image', ['imagemin']);
	        grunt.registerTask('html', ['htmlmin']);
	        grunt.registerTask('js', ['concat:js', 'uglify:minjs']);
	        grunt.registerTask('compress_js', ['uglify:minjs']);
	        grunt.registerTask('compress_css', ['cssmin']);
	        // 定义默认任务

	        // grunt.registerTask('dev', ['csslint', 'jshint']);
	        // grunt.registerTask('dest', ['imagemin', 'concat:css', 'cssmin', 'uglify:minjs']);
	        /************    注册frunt 任务    ************/
	    };


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