Gruntfile.js 15.2 KB
"use strict";
var LIVERELOAD_PORT, lrSnippet, mountFolder;
/*解决跨域问题*/
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

LIVERELOAD_PORT = 35728;

/*页面自动刷新,即代码有修改页面就自动刷新*/
lrSnippet = require("connect-livereload")({
    port: LIVERELOAD_PORT
});

mountFolder = function(connect, dir) {
    return connect["static"](require("path").resolve(dir));
};

module.exports = function(grunt) {
    var yeomanConfig;
    /*自动读取并加载项目 packge.json 文件中 devDependencies 配置下以 grunt-* 开头的依赖库*/
    require("load-grunt-tasks")(grunt);
    /*构建完成后,会给出每个任务的耗时及占总耗时的百分比*/
    require("time-grunt")(grunt);
    yeomanConfig = {
        app: "src/main/websrc",
        dist: "dist",
        docs: "documentation"
    };

    grunt.initConfig({
        yeoman: yeomanConfig,
        watch: {
            compass: {
                files: ["<%= yeoman.app %>/styles/**/*.{scss,sass}"],
                tasks: ["compass:server"]
            },

            livereload: {
                options: {
                    livereload: LIVERELOAD_PORT  //或者true
                },
                files: [
                    "<%= yeoman.app %>/index.html",
                    "<%= yeoman.app %>/template/**/*.html",
                    "<%= yeoman.app %>/js/**/*.js",
                    "<%= yeoman.app %>/styles/**/*.scss",
                    ".tmp/styles/**/*.css",
                    "<%= yeoman.app %>/images/**/*.{png,jpg,jpeg,gif,webp,svg}"
                ]
            }
        },
        connect: {
            proxies: [{
                context: ['/api'],
                host: 'localhost',
                // host: '192.168.2.37',
                port: 8091,
                https: false,
                xforward: true,
                hideHeaders: ['x-removed-header']
            }],
            options: {
                port: 9008,
                hostname: "*"
            },
            livereload: {
                options: {
                    middleware: function (connect) {
                        return [lrSnippet, mountFolder(connect, ".tmp"), mountFolder(connect, yeomanConfig.app), proxySnippet];
                    }
                }
            },
            test: {
                options: {
                    middleware: function (connect) {
                        return [mountFolder(connect, ".tmp"), mountFolder(connect, "test")];
                    }
                }
            },
            dist: {
                options: {
                    middleware: function (connect) {
                        //return [mountFolder(connect, yeomanConfig.dist)];
                        return [lrSnippet, mountFolder(connect, yeomanConfig.dist), proxySnippet];
                    }

                }
            }
        },
        open: {
            server: {
                url: "http://localhost:<%= connect.options.port %>"
            }
        },
        clean: {
            dist: {
                files: [
                    {
                        dot: true,
                        src: [".tmp", "<%= yeoman.dist %>/*", "!<%= yeoman.dist %>/.git*"]
                    }
                ]
            },
            all: [".tmp", ".sass-cache", "readme.md", "node_modules", ".git"],
            server: ".tmp"
        },
        jshint: { //代码质量检查
            options: {
                jshintrc: ".jshintrc"
            },
            all: ["Gruntfile.js", "<%= yeoman.app %>/app/**/*.js"]
        },
        injector: { // JS/CSS 自动注入工具, 可以自动将 JS/CSS 的引用注入到 HTML 文件中
            options: {
                relative: true
            },
            local_dependencies: {
                files: {
                    "<%= yeoman.app %>/index.html": [
                        "<%= yeoman.app %>/app/**/*.module.js",
                        "<%= yeoman.app %>/app/**/*.js",
                        "!" + "<%= yeoman.app %>/**/*.spec.js",
                        "<%= yeoman.app %>/**/*.css"
                    ]
                }
            }
        },
        compass: {
            options: {
                sassDir: "<%= yeoman.app %>/styles",
                cssDir: ".tmp/styles",
                imagesDir: "<%= yeoman.app %>/images/",
                javascriptsDir: "<%= yeoman.app %>/js",
                httpFontsPath: "fonts",
                relativeAssets: true
            },
            dist: {
                options: {
                    outputStyle: 'compressed',
                    debugInfo: false,
                    noLineComments: true
                }
            },
            server: {
                options: {
                    debugInfo: true
                }
            },
            forvalidation: {
                options: {
                    debugInfo: false,
                    noLineComments: false
                }
            }
        },

        useminPrepare: {
            html: ["<%= yeoman.app %>/index.html","<%= yeoman.app %>/login.html","<%= yeoman.app %>/activation.html","<%= yeoman.app %>/failure.html","<%= yeoman.app %>/forget.html","<%= yeoman.app %>/register.html","<%= yeoman.app %>/success.html","<%= yeoman.app %>/resetpwd.html","<%= yeoman.app %>/olduser.html","<%= yeoman.app %>/demo.html","<%= yeoman.app %>/home.html","<%= yeoman.app %>/main.html"],
            options: {
                dest: "<%= yeoman.dist %>",
                flow: {
                    steps: {
                        js: ["concat"],
                        css: ["concat"] //concat,cssmin
                    },
                    post: []
                }
            }
        },
        usemin: {
            html: ["<%= yeoman.dist %>/**/*.html"],
            options: {
                dirs: ["<%= yeoman.dist %>"],
                blockReplacements: {
                    css:function (block) {
                        var final_name = block.dest;
                        final_name += "?r="+Math.random();
                        var media = block.media ? ' media="' + block.media + '"' : '';
                        return '<link rel="stylesheet" href="' + final_name + '"' + media + '>';//此处为css标签的定制
                    },
                    js:function (block) {
                        var final_name = block.dest;
                        final_name += "?r="+Math.random();
                        var defer = block.defer ? 'defer ' : '';
                        var async = block.async ? 'async ' : '';
                        return '<script ' + defer + async + 'src="' + final_name + '"><\/script>';//次处为js标签的定制
                    }
                }
            }
        },
        htmlmin: {
            dist: {
                options: {},
                files: [
                    {
                        expand: true,
                        cwd: "<%= yeoman.app %>",
                        src: ["*.html", "template/**/*.html"],
                        dest: "<%= yeoman.dist %>"
                    }
                ]
            }
        },
        copy: {
            dist: {
                files: [
                    {
                        expand: true,
                        dot: true,
                        cwd: "<%= yeoman.app %>",
                        dest: "<%= yeoman.dist %>",
                        src: [
                            "data/**/*",
                            "font/**/*",
                            "images/**/*",
                            "**/*.html",
                            "template/**/*.png",
                            "template/**/*.jpg",
                            "*.ico"
                        ]
                    },
                    {
                        expand: true,
                        cwd: ".tmp/images",
                        dest: "<%= yeoman.dist %>/images",
                        src: ["generated/*"]
                    },
                    {
                        expand: true,
                        cwd: "",
                        dest: "<%=yeoman.dist%>",
                        src: ["Gruntfile.js",'test/**/*']
                    }
                ]
            },
            styles: {
                // expand: true,
                // cwd: "<%= yeoman.app %>/styles",
                // dest: ".tmp/styles/",
                // src: "**/*.css"
            }
        },
        concurrent: {
            server: ["compass:server", "copy:styles"],
            dist: ["compass:dist", "copy:styles", "htmlmin"]
        },
        cssmin: {
            options: {
                keepSpecialComments: '0'
            },
            build: {
                files:{
                    "<%= yeoman.dist %>/styles/index.css":[".tmp/styles/*.css","<%= yeoman.app %>/styles/*.css","!.tmp/styles/login.css","!.tmp/styles/home.css"],
                    "<%= yeoman.dist %>/styles/login.css":[".tmp/styles/login.css"],
                    "<%= yeoman.dist %>/styles/home.css":[".tmp/styles/home.css"]
                }
            }
        },
        concat: {
            options: {
                separator: grunt.util.linefeed + ';' + grunt.util.linefeed
            },
            // cssbuild: {
            //     src: ".tmp/styles/*.css",
            //     dest: "<%= yeoman.dist %>/styles/app.css"
            // },
            dist: {}
        },
        uglify: {
            options: {
                mangle: true, //混淆变量名
                compress: {
                    drop_console: true
                }
            },
            dist: { // if do this uglify for app, the app can not start up
                files: {
                    "<%= yeoman.dist %>/scripts/app.js": ["<%= yeoman.dist %>/scripts/app.js"],
                    "<%= yeoman.dist %>/scripts/ui.js": ["<%= yeoman.dist %>/scripts/ui.js"],
                    "<%= yeoman.dist %>/scripts/lgui.js": ["<%= yeoman.dist %>/scripts/lgui.js"],
                    "<%= yeoman.dist %>/scripts/regui.js": ["<%= yeoman.dist %>/scripts/regui.js"],
                    "<%= yeoman.dist %>/scripts/change.js": ["<%= yeoman.dist %>/scripts/change.js"],
                    "<%= yeoman.dist %>/scripts/failure.js": ["<%= yeoman.dist %>/scripts/failure.js"],
                    "<%= yeoman.dist %>/scripts/forget.js": ["<%= yeoman.dist %>/scripts/forget.js"],
                    "<%= yeoman.dist %>/scripts/register.js": ["<%= yeoman.dist %>/scripts/register.js"],
                    "<%= yeoman.dist %>/scripts/success.js": ["<%= yeoman.dist %>/scripts/success.js"],
                    "<%= yeoman.dist %>/scripts/resetpwd.js": ["<%= yeoman.dist %>/scripts/resetpwd.js"],
                    "<%= yeoman.dist %>/scripts/olduser.js": ["<%= yeoman.dist %>/scripts/olduser.js"]
                 }
            }
        },

        mock: { //currently just list all mock api in this files, we need  to separate them based the module.
            your_target: {
                options: {
                    port: 9001,
                    delay: 200,
                    cookie: {},
                    placeholders: {
                        getNumArr: function (len) { //返回len个随机整数
                            var arr = [];
                            for(var i=0;i<len;i++){
                                arr.push(this.d1000());
                            }
                            return arr;
                        },
                        getFloatArr: function (len) { //返回len个随机浮点数
                            var arr = [];
                            for(var i=0;i<len;i++){
                                arr.push(this.float(0,100,0,2));
                            }
                            return arr;
                        },
                        getLastDates: function (len,hasToday) {  //返回最近len天数据,hasToday为true从今天开始往前推
                            var arr = [];
                            var dd = new Date(),d = dd.getDate();
                            var m = d,start = 1,end = len;
                            if(hasToday && hasToday==true){
                                start = 0;
                                end -= 1;
                            }
                            for(var i=start;i<=end;i++){
                                var day = m - i;
                                if(day == 0){
                                    dd.setDate(m-i);
                                    m += dd.getDate();
                                }
                                else{
                                    dd.setDate(m-i);
                                }

                                arr.unshift(this.date(dd,'YYYY-MM-DD'));
                            }
                            return arr;
                        },
                        getLastDay: function (len) { //返回最近第len天,0是当天
                            var dd = new Date(),d = dd.getDate();
                            dd.setDate(d-len);
                            return this.date(dd,'YYYY-MM-DD')
                        },
                        getLastMonth: function (len) { //返回最近第len月的第一天,0是当月,eg:2017-03-01
                            var dd = new Date(),m = dd.getMonth();
                            dd.setMonth(m-len);
                            dd.setDate(1);
                            return this.date(dd,'YYYY-MM-DD')
                        },
                        getLastWeek: function (len) { //返回最近第几周的周一,0是当周的周一
                            var dd = new Date(),d = dd.getDate(),w = dd.getDay();
                            w = w == 0 ? 7 : w;
                            dd.setDate(d-w+1-len*7);
                            return this.date(dd,'YYYY-MM-DD');
                        },
                        getHourData: function (num,hour) { //根据小时对比返回当前应显示数
                            var nh = new Date().getHours();
                            if(nh>=hour){
                                return num;
                            }
                            else{
                                return 0;
                            }
                        }
                    },
                    route: {

                    }
                },
                cwd: './test/mocks',
                src: ['*.json']
            }
        }
    });
    // grunt.registerTask("docs", function() {
    //     return grunt.task.run(["jade:docs", "connect:docs", "open", "watch"]);
    // });
    grunt.registerTask("server", function(target) {
        if (target === "dist") {
            return grunt.task.run(["serve:dist"]);
        }
        return grunt.task.run(["serve"]);
    });

    grunt.registerTask("serve", function(target) {
        if (target === "dist") {
            //return grunt.task.run(["build", "open", "connect:dist:keepalive"]);

            return grunt.task.run(["build", "configureProxies",  "connect:dist:keepalive" , "open"]);
        }
        return grunt.task.run(["clean:server", "concurrent:server", "configureProxies", "connect:livereload", "open", "watch"]);
    });

    grunt.registerTask("build", ["clean:dist", "useminPrepare", "concurrent:dist", "copy:dist", "concat", "cssmin", "uglify", "usemin"]);

    return grunt.registerTask("default", ["build"]);
};