使用GruntJS連結與壓縮多個JavaScript檔案

來源:互聯網
上載者:User

使用GruntJS連結與壓縮多個JavaScript檔案

自己寫了個簡單的HTML5 Canvas的圖表庫,可以支援餅圖,折線圖,散佈圖,盒子圖

柱狀圖,同時支援滑鼠提示,繪製過程動畫效果等。最終我想把這些多個JS檔案變成

一個JS檔案發布出去,於是我的問題來啦,怎麼把這些JS檔案搞成一個啊,群裡有個

朋友告訴我,GruntJS – JavaScript多檔案編譯,風格檢查,連結與壓縮神器。Google了一

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

 

一什麼是GruntJS

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

二:安裝與運行

它的官方教程說的不是很清楚,有點讓第一次看的人云裡霧裡的。我總結一下,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']);}

四:運行結果

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.