关于grunt实现js,html,css编译压缩

简单来说项目发布生产往往网站加载的效率,web项目提交效率有gzip等方式,

今天我们就共学习一下用grunt来最项目压缩。

首先要使用grunt就要先安装grunt,具体的安装方式 -----百度,这里不多讲。

        

        等一切都配置ok后你只需要在控制台输入grunt   build命令,执行编译后你就会看到项目中会多一文件,而这个文件中的内容跟项目中的一模一样,知识不同的是这个文件下的文件都是压缩过的,据测试压缩够厚的文件是源文件的1/4左右,这就会大大减少加载量,还有的不同就是,你的index.html上面之前所加载的.css文件通通消失,就剩下一个.css文件,这个文件就是你所配制的.css文件,因为grunt已经把所有的.css文件压缩成一个.css文件。


好,一个简单的命令就可以使你的项目实现压缩,并且提高效率,那我们就看一下grunt是怎么做到的。


1,配置文件。

大家在github上都可以看到package.json文件,

package.json

"devDependencies": {
    "grunt": "~0.4.2",
    "grunt-autoprefixer": "^1.0.1",
    "grunt-concurrent": "^1.0.0",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-concat": "~0.3.0",
    "grunt-contrib-connect": "~0.5.0",
    "grunt-contrib-copy": "~0.5.0",
    "grunt-contrib-cssmin": "~0.9.0",
    "grunt-contrib-jshint": "~0.7.1",
    "grunt-contrib-uglify": "~0.4.0",
    "grunt-contrib-watch": "~0.5.2",
    "grunt-contrib-htmlmin": "~0.3.0",
    "grunt-contrib-imagemin": "~0.9.1",
    "grunt-filerev": "^2.1.1",
    "grunt-newer": "~0.5.4",
    "grunt-pagespeed": "^0.3.0",
    "grunt-usemin": "~2.0.2",
    "load-grunt-tasks": "~0.4.0",
    "time-grunt": "~0.2.1"
  },
而这些配置就是grunt能够执行基础。控制台执行命令npm install

会看到项目根目录会有node_modules文件夹,这就是grunt所依赖的包。


除此之外还有。

就是Gruntfile.js文件 Gruntfile.js 文件就是 就是grunt 命令所依赖的js.

// Generated on 2013-11-25 using generator-angular 0.6.0-rc.2
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    // Define the configuration for all the tasks
    grunt.initConfig({

        // Project settings
        yeoman: {
            // configurable paths
            app: 'app',
            dist: 'dist'
        },
        // Watches files for changes and runs tasks based on the changed files
        watch: {
            js: {
                files: ['{.tmp,<%= yeoman.app %>}/assets/js/{,*/}*.js'],
                tasks: ['newer:jshint:all']
            },
//            jsTest: {
//                files: ['test/spec/{,*/}*.js'],
//                tasks: ['newer:jshint:test', 'karma']
//            },
//            styles: {
//                files: ['<%= yeoman.app %>/assets/css/{,*/}*.css'],
//                tasks: ['newer:copy:styles', 'autoprefixer']
//            },
            gruntfile: {
                files: ['Gruntfile.js']
            },
            livereload: {
                options: {
                    livereload: '<%= connect.options.livereload %>'
                },
                files: [
                    '<%= yeoman.app %>/{,*/}*.html',
                    '<%= yeoman.app %>/assets/css/{,*/}*.css',
                    '.tmp/assets/css/{,*/}*.css',
                    '<%= yeoman.app %>/assets/img/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },

        // The actual grunt server settings
        connect: {
            options: {
                port: 8080,
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: '0.0.0.0',
                livereload: 35728
            },
            livereload: {
                options: {
                    open: true,
                    base: [
                        '.tmp',
                        '<%= yeoman.app %>'
                    ]
                }
            },
            dist: {
                options: {
                    port: 8081,
                    hostname: '0.0.0.0',
                    base: '<%= yeoman.dist %>',
                    livereload: 35728
                }
            }
        },

        // Make sure code styles are up to par and there are no obvious mistakes
        jshint: {
            options: {
                //jshintrc: 'test/.jshintrc'
//                reporter: require('jshint-stylish')
            },
            all: [
                'Gruntfile.js',
                '<%= yeoman.app %>/assets/js/{,*/}*.js'
            ],
            test: {
                options: {
                    //jshintrc: 'test/.jshintrc'
                },
                src: ['test/spec/{,*/}*.js']
            }
        },

        // Empties folders to start fresh
        clean: {
            dist: {
                files: [{
                    dot: true,
                    src: [
                        '.tmp',
                        '<%= yeoman.dist %>/*',
                        '!<%= yeoman.dist %>/.git*'
                    ]
                }]
            },
            oldcss: {
                src: [
                    '<%= yeoman.dist %>/assets/css/*.css'
                ]
            },
            oldjs: {
                src: [
                    '<%= yeoman.dist %>/assets/js/modernizr.js',
                    '<%= yeoman.dist %>/PolyfillLoader.js'
                ]
            }
        },

        // Add vendor prefixed styles
        autoprefixer: {
            options: {
                browsers: ['last 2 version']
            },
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/assets/css/',
                    src: '{,*/}*.css',
                    dest: '.tmp/assets/css/'
                }]
            }
        },


        // Reads HTML for usemin blocks to enable smart builds that automatically
        // concat, minify and revision files. Creates configurations in memory so
        // additional tasks can operate on them
        useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: 'dist'
            }
        },


        // Performs rewrites based on rev and the useminPrepare configuration
        usemin: {
            html: ['<%= yeoman.dist %>/index.html']
        },

        // The following *-min tasks produce minified files in the dist folder
        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>',
                    src: '{,*/}*.{png,jpg,jpeg,gif,svg}',
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },
        uglify:{
            options: {
                mangle: false
            },
            dist: {
                files: [
                    {expand: true,
                    cwd: '<%= yeoman.app %>',
                    src: [
                        '**/*.js',
                        '!common/config.js',
                        '!assets/js/mc-apple/mc.apple.1.0.0.js'
                        ],
                    dest: '<%= yeoman.dist %>' }
                ]
            }
        },
        svgmin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/assets/img',
                    src: '{,*/}*.svg',
                    dest: '<%= yeoman.dist %>/assets/img'
                }]
            }
        },
        htmlmin: {

            dist: {
                options: {
//                    Optional configurations that you can uncomment to use
                    removeCommentsFromCDATA: true,
                      removeComments: true,
                    collapseWhitespace: true,
                    collapseBooleanAttributes: true,
                    removeAttributeQuotes: true,
                    removeRedundantAttributes: true,
                    useShortDoctype: true,
                    removeEmptyAttributes: true,
                    removeOptionalTags: true
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.dist %>',
                    src: [
                        '**/*.html',
                        '!template/icons/**/*.html',
                        '!home/**/*.html',
                        '!cart/cart.step3.tpl.html',
                        '!my/profile/emailvalidate.tpl.html',
                        '!index.html'
                        ],
                    dest: '<%= yeoman.dist %>'
                }],
                dev: {// Another target
                    files: {
                        cwd: '<%= yeoman.dist %>',
                        src: [
                            '**/*.html',
                            '!template/icons/**/*.html',
                            '!home/**/*.html',
                            '!cart/cart.step3.tpl.html',
                            '!my/profile/emailvalidate.tpl.html',
                            '!index.html'

                            ],
                        dest: '<%= yeoman.dist %>'
                    }
                }
            }
        },


//
//        // Copies remaining files to places other tasks can use
        copy: {
            main: {
                src: '<%= yeoman.app %>/index.html',
                dest: '<%= yeoman.dist %>/index.html'
            },
            dist: {
                expand: true,
                cwd: '<%= yeoman.app %>/',
                src: ['**',
                    '!WEB-INF',
                    '!WEB-INF/**/*',
                    '!META-INF',
                    '!META-INF/**/*',
                    '!staticpage',
                    '!staticpage/**/*',
                    '!assets/js/baidu/baidu.js',
                    '!common/config.js'
                ],
                dest: '<%= yeoman.dist %>/'

            }
        },
        //
        //pagespeed: {
        //    options: {
        //        nokey: true,
        //        //url: "localhost:8080"
        //        url: "http://www.maguscreation.com"
        //    }
        //    //,
        //    //prod: {
        //    //    options: {
        //    //        //url: "localhost:8081",
        //    //        url: "http://www.maguscreation.com",
        //    //        locale: "zh-cn",
        //    //        strategy: "desktop",
        //    //        threshold: 80
        //    //    }
        //    //}
        //}
        pagespeed: {
            options: {
                //nokey: true,
                key: "AIzaSyCU7fxCaF5epTmGtvY6oF-Ucqigz44XdtE",
                url: "https://developers.google.com"
            },
            prod: {
                options: {
                    url: "https://developers.google.com/speed/docs/insights/v1/getting_started",
                    locale: "en_GB",
                    strategy: "desktop",
                    threshold: 80
                }
            },
            paths: {
                options: {
                    paths: ["/speed/docs/insights/v1/getting_started", "/speed/docs/about"],
                    locale: "en_GB",
                    strategy: "desktop",
                    threshold: 80
                }
            }
        },

        // Run some tasks in parallel to speed up the build process
        concurrent: {
            min: [
                //'imgmin:dist'
                //'svgmin'
                //'htmlmin:dist'
            ]
        }


        // Test settings
//        karma: {
//            unit: {
//                configFile: 'karma.conf.js',
//                singleRun: true
//            }
//        }
    });


    grunt.registerTask('serve', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['connect:dist', 'watch']);
        }

        grunt.task.run([
//            'clean:server',
//            'concurrent:server',
//            'autoprefixer',
//            'connect:livereload'
            'connect',
            'watch'
        ]);
    });

    grunt.registerTask('test', [
//        'clean:server',
//        'concurrent:test',
//        'autoprefixer',
//        'connect:test'
//        'karma'
    ]);

    grunt.registerTask('build', [
        'clean:dist',
        'copy:dist',
        'clean:oldcss',
//        'clean:oldjs',
        'useminPrepare',
        'concat:generated',
//        'autoprefixer',
        'cssmin:generated',
        'uglify',
//        'uglify:generated',
        //'filerev',
//        'concurrent:min',
        'usemin',
        'htmlmin',
        'imagemin'
        //'connect:dist'

    ]);

    grunt.registerTask('speed', [
        'pagespeed'
    ]);

    grunt.registerTask('default', [
        'serve',
        'newer:jshint'
//        'test',
//        'build'
    ]);
};

在最后index.html中加上

  <!-- build:css assets/css/apple.min.css -->
<pre name="code" class="html">  <!-- endbuild -->

 的组合例如: 

  <!-- build:css assets/css/apple.min.css -->
    <link rel="stylesheet" href="assets/css/angular.css" />
<pre name="code" class="html">    <link rel="stylesheet" href="assets/css/bootstrap.css" />
    <link rel="stylesheet" href="assets/css/bootstrap.css" />
    <link rel="stylesheet" href="assets/css/bootstrap.3.css" />
<!-- endbuild -->

 

 最后就之会有一个
apple.min.css了。







  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值