基於Gruntjs的Web前端基礎構建工具

Grunt現在已經是前端開發必不可少的工具了,下面我把經常使用的Grunt插件整理了一下,集成了一個基礎性的項目構建工具:css

 

package.json:html

{
  "name": "demo",
  "version": "1.0.0",
  "author":"yushengjie",
  "description": "基礎grunt構建",
  "devDependencies": {
    "grunt-contrib-clean": "~0.5.0",
    "grunt-contrib-uglify": "~0.2.0",
    "grunt-contrib-concat": "^0.4.0",
    "grunt-contrib-copy": "^0.5.0",
    "grunt-contrib-jshint": "^0.10.0",
    "grunt-contrib-mincss": "^0.3.2",
    "grunt-contrib-cssmin": "^0.9.0",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-contrib-imagemin": "^0.6.1",
    "grunt-contrib-htmlmin": "^0.2.0",
    "karma-script-launcher": "~0.1.0",
    "karma-chrome-launcher": "~0.1.2",
    "karma-firefox-launcher": "~0.1.3",
    "karma-ie-launcher": "~0.1",
    "karma-phantomjs-launcher": "~0.1.2",
    "karma": "~0.10.0",
    "karma-jasmine": "~0.2.0",
    "karma-story-reporter": "~0.2.2",
    "grunt-karma": "~0.6.2",
    "grunt-cli": "~0.1.13",
    "karma-sauce-launcher": "~0.1.8"
  }
}

 

Gruntfile.js:前端

/**
 * 項目基礎Grunt構建,包含如下功能:
 *      文件清理,
 *      js語法檢查,
 *      css合併壓縮,
 *      圖片壓縮,
 *      html壓縮,
 *      js合併,
 *      js壓縮,
 *      監聽js修改,
 *      圖片中線上路徑替換爲本地路徑,
 *      自動化單元測試
 * @author: yushengjie
 * @since: 2014-04-03
 * @desc: 請預先安裝Node.js,grunt-cli。進到該目錄之後cmd輸入npm install,等待安裝node模塊。
 *        安裝好之後,能夠輸入如下三種命令:
 *        $> grunt:默認命令,包含js合併壓縮,css合併壓縮等操做
 *        $> grunt w:js文件修改監聽命令
 *        $> grunt k:自動化單元測試,在karma.conf.js裏能夠配置須要測試的瀏覽器,採用jasmine測試框架
 *
 */
module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        /**
         * 清理目錄
         */
        clean: {
            options: {
                force: true
            },
            target: 'dest'
        },

        /**
         * js語法檢查
         */
        jshint: {
            options: {
                curly: true,
                eqeqeq: true,
                newcap: true,
                noarg: true,
                sub: true,
                boss: true,
                node: true
            },
            files: {
                src: ['scripts/*.js']
            }
        },

        /**
         * css合併壓縮
         */
        cssmin: {
            target: {
                files: {
                    'dest/css/dest.css': ['css/one.css','css/two.css']
                }
            }
        },

        /**
         * css中圖片路徑替換,把線上的地址改成本地路徑
         */
        replace: {
            dest: {
                options: {
                      patterns: [
                        {
                          match: /http(s?):\/\/(\S+?)(\w+)\.(jpg|png|gif)/gi,
                          replacement: '../images/$3.$4'
                        }
                      ]
                },
                files: [
                    {
                        expand: true, 
                        flatten: true,  
                        src: ['dest/css/*.css'],
                        dest: 'dest/css/'
                    }
                ]
            }
        },

        /**
         * 圖片壓縮
         */
        imagemin: {
            dynamic: {
                files: [{
                    expand: true, 
                    cwd: 'images/',
                    src: ['**/*.{png,jpg,gif}'],
                    dest: 'dest/images/'
                }]
            }
        },

        /**
         * html壓縮
         */
        htmlmin: {
            dest: {
                options: {
                    removeComments: true,
                    collapseWhitespace: true
                },
                files: {
                    'index.html': 'index_source.html'
                }
            }
        },

        /**
         * js合併
         */
        concat: {
            options: {
                separator: ";",
                stripBanners: true,
                banner: '/*! <%= pkg.name %> - <%= pkg.version %> - ' +
                            '<%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            target: {
                src:  ['scripts/*.js'],
                dest: 'dest/scripts/output.js'
            }
        },

        /**
         * js壓縮
         */
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            target: {
                src: 'dest/scripts/output.js',
                dest: 'dest/scripts/output.min.js'
            }
        },

        /**
         * 監聽js修改
         */
        watch: {
            options: {
                spawn: false,
                livereload: true
            },
            scripts: {
                files: ['scripts/*.js'],
                tasks: ['jshint','concat','uglify']
            }
        },

        /**
         * 單元測試
         */
        karma: {
            unit: {
                configFile: 'karma.conf.js'
            }
        }
    });

    /**
     * 加載grunt插件
     */
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-imagemin');
    grunt.loadNpmTasks('grunt-contrib-htmlmin');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-replace');
    grunt.loadNpmTasks('grunt-karma');

    
    /**
    * 默認命令:grunt
    */
    grunt.registerTask('default', ['clean','jshint','cssmin','replace','imagemin','htmlmin','concat','uglify']);

    /**
    * 構建JS
    */
    grunt.registerTask('js', ['jshint','concat','uglify']);
    
    /**
    * 監聽JavaScript文件的修改:grunt w
    */
    grunt.registerTask('w', ['watch']);

    /**
    * 自動迴歸jasmine單元測試:grunt k
    */
    grunt.registerTask('k', ['karma']); 
}

能夠執行四個grunt命令:node

grunt, grunt js, grunt w, grunt k。功能在上面代碼的註釋中寫了。執行結果截圖以下:git

karma配置文件:angularjs

module.exports = function(config) {
    config.set({
 
        // base path, that will be used to resolve files and exclude
        basePath: '',
 
        // frameworks to use
        frameworks: ['jasmine'],
 
        // list of files / patterns to load in the browser
        files: [
            'scripts/**/*.js','test/**/*.js'
        ],
 
        // list of files to exclude
        exclude: [
        ],
 
        // test results reporter to use
        reporters: ['progress'],
 
        // web server port
        port: 9876,
 
        // enable / disable colors in the output (reporters and logs)
        colors: true,
 
        // level of logging
        logLevel: config.LOG_INFO,
 
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,
 
        // Start these browsers
        browsers: ['Chrome','IE','Firefox','PhantomJS'],
 
        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 60000,
 
        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false
    });
};

browsers: ['Chrome','IE','Firefox','PhantomJS']

  注意安裝了chrome,firefox,ie的啓動插件才能夠在運行自動化測試命令時自動啓動瀏覽器,PhantomJS是無瀏覽器的測試環境,這裏未安裝,提示未註冊。github

 

測試框架採用jasmine,web

Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests. This guide is running against Jasmine version 2.0.0.chrome

Jasmine是一個行爲驅動開發的js測試框架。他不依賴與其餘js框架,不須要DOM。他有簡潔,顯式的語法,能夠輕鬆的編寫測試代碼。npm

http://jasmine.github.io/2.0/introduction.html

 

karma:test runner,集成jasmine,

On the AngularJS team, we rely on testing and we always seek better tools to make our life easier. That's why we created
Karma - a test runner that fits all our needs.

The main goal for Karma is to bring a productive testing environment to developers. The environment being one where they don't have to set up loads of configurations, but rather a place where developers can just write the code and get instant feedback from their tests. Because getting quick feedback is what makes you productive and creative.

在angularJS的團隊,咱們依賴測試,爲了讓咱們的生活更簡單總在尋找更高效的測試工具。這就是爲何咱們建立了Karma---一個測試執行器。

Karma的主要目的是給開發人員帶來一種產品級的測試環境。這個測試環境不須要作大量的配置工做,開發者只須要編寫代碼就能夠瞬間獲得測試反饋。由於快速獲得測試反饋可讓你有更好的生產效率和創造力。

http://karma-runner.github.io/0.12/index.html

 

 

Grunt集成了karma和jasmine,很是方便的進行測試。

相關文章
相關標籤/搜索