使用GruntJS連接與壓縮多個JavaScript文件

使用GruntJS連接與壓縮多個JavaScript文件javascript

本身寫了個簡單的HTML5 Canvas的圖表庫,能夠支持餅圖,折線圖,散點圖,盒子圖html

柱狀圖,同時支持鼠標提示,繪製過程動畫效果等。最終我想把這些多個JS文件變成html5

一個JS文件發佈出去,因而個人問題來啦,怎麼把這些JS文件搞成一個啊,羣裏有個java

朋友告訴我,GruntJS – JavaScript多文件編譯,風格檢查,連接與壓縮神器。Google了一node

把終於幫我完成這個任務,算是入門,分享一下過程。npm

 

一什麼是GruntJSjson

不想翻譯英文,本身看它的網站吧->http://gruntjs.com/canvas

二:安裝與運行windows

它的官方教程說的不是很清楚,有點讓第一次看的人云裏霧裏的。我總結一下,GruntJS服務器

是基於與依賴服務器node.js的。因此首先第一步是下載並安裝node.js,下載地址:

http://nodejs.org/download/

 

第二步:運行安裝grunt命令行工具– 目的是爲了使用grunt命令

只有在windows的命令行窗口中運行:npm install -g grunt-cli便可。

更具體的解釋參見這裏:http://gruntjs.com/getting-started

 

第三步:在項目的根目錄建立project.json與Gruntfile.js兩個文件

由於grunt的task運行要依賴於這兩個文件。

其中建立project.json文件方法能夠經過命令行實現:nmp init我建立project.json

內容以下:

{

 "name": "fishchart",

 "version": "0.0.1",

 "description": "html5 canvas chart library",

 "author": "zhigang",

 "license": "BSD",

 "devDependencies": {

   "grunt": "~0.4.1",

   "grunt-contrib-uglify": "~0.2.2",

   "grunt-contrib-jshint": "~0.6.2",

   "grunt-contrib-concat": "~0.3.0"

  }

}

使用命令建立時候,若是你不知道寫什麼直接回車跳過便可。

 

三: 安裝與使用Grunt Plug-in完成javascript文件連接與壓縮
1.  安裝javascript文件連接插件支持

npm install grunt-contrib-concat --save-dev

2. 安裝javascript文件壓縮插件支持
npm install grunt-contrib-uglify --save-dev
3. 在Gruntfile.js文件中配置選項,加載與定義task

 

module.exports = function(grunt) {
 
    grunt.initConfig({
 
        //our JSHint options
        jshint: {
            all: ['main.js'] //files to lint
        },
 
        //our concat options
        concat: {
            options: {
                separator: ';' //separates scripts
            },
            dist: {
                src: ['js/*.js', 'js/**/*.js'], //Grunt mini match for your scripts to concatenate
                dest: 'js/fishchart_v0.0.1.js' //where to output the script
            }
        },
 
        //our uglify options
        uglify: {
            js: {
                files: {
                    'js/fishchart_v0.0.1.js': ['js/fishchart_v0.0.1.js'] //save over the newly created script
                }
            }
        }
 
    });
 
    //load our tasks
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
 
    // default tasks to run
    // grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
	grunt.registerTask('development', ['jshint']);
	grunt.registerTask('production', ['jshint', 'concat', 'uglify']);
	}


四:運行結果

 

最後還想贊一下,這個東西太好用啦!

相關文章
相關標籤/搜索