標籤:
再探 butterfly.js - grunt.js篇(一) 神器 grunt.js
久仰grunt.js的大名,學習grunt.js一直是我todo List的第一位。趁著新春佳節來臨之際(打醬油的日子),就來填了這個坑,完了這個心愿。
grunt.js的強大,強大在於它擁有很多用途豐富的外掛程式,和不同外掛程式之間的聯動實現更牛逼的功能。
這裡預設大家已經安裝了npm和會用npm install等指令,就不詳細講了。下面講用到grunt-contrib-watch和grunt-contrib-connect實現改動代碼自動重新整理瀏覽器,而不用手動按F5或者ctrl+R來重新整理瀏覽器。也會將這個酷炫的測試功能應用於butterfly.js的應用開發之中。
grunt-contrib-watch
grunt-contrib-watch,這個外掛程式超級強大,基本上,我見到用grunt.js的應用開發,沒有那個不用到grunt-contrib-watch。其功能就是:監測指定檔案的改動包括:html、css、js,當指定的檔案有改動(儲存後),就會觸發task。
grunt-contrib-connect
grunt-contrib-connect,文檔上面,它給自己的定義就是一個connect web server,所以,這是一個可以建立伺服器的外掛程式。
正片
建立我們的工程目錄:
myproject ┣app ┣butterfly ┗main ┣theme.css ┣index.html ┗index.js ┣package.json ┗Gruntfile.js
package.json可以用npm init來建立,或者自己建立檔案。這個屬於npm基礎,不瞭解的自己面壁。在命令列執行以下代碼:
npm install grunt --save-devnpm install grunt-contrib-connect --save-devnpm install grunt-contrib-watch --save-dev
上面的--save-dev是兩根--的,不知道為什麼被吞了一根,這三行代碼,分別安裝了grunt、grunt-contrib-connect、grunt-contrib-watch。
編輯Gruntfile.js,這個檔案是Grunt.js的核心,所有Grunt.js執行的任務都在這裡控制,Grunt.js的原始狀態應該是這樣的:
module.exports = function(grunt){ pkg: grunt.file.readJSON(‘package.json‘), grunt.initConfig({ //... });}
先設定connect模組:
connect: { options: { port: 9000, hostname: ‘localhost‘, livereload: 35729 }, server: { options: { open: {target:‘http://localhost:9000/main/index.html‘}, base: [‘app‘] } }}
再設定watch模組:
watch: { livereload: { options: { livereload: true }, files: [‘app/main/index.html‘,‘app/main/theme.css‘, ‘app/main/index.js‘] }}
最後設定task
module.exports = function(grunt){ pkg: grunt.file.readJSON(‘package.json‘), grunt.initConfig({ connect: { options: { port: 9000, hostname: ‘localhost‘, livereload: 35729 }, server: { options: { open: {target:‘http://localhost:9000/main/index.html‘}, base: [‘app‘] } } }, watch: { livereload: { options: { livereload: true }, files: [‘app/main/index.html‘,‘app/main/theme.css‘, ‘app/main/index.js‘] //監測檔案清單 } } }); grunt.loadNpmTasks(‘grunt-contrib-connect‘); grunt.loadNpmTasks(‘grunt-contrib-watch‘); grunt.registerTask(‘default‘, [‘connect:server‘, ‘watch‘])}
編輯完成後,在命令列輸入grunt,grunt.js通過grunt-contrib-connect建立一個伺服器,localhost:9000(網域名稱和連接埠在options設定),執行命令後,你會發現瀏覽器自動開啟了http://localhost:9000/main/index.html。如果沒有報錯,就算是大功告成了。這時候你可以改動一下index.html、theme.css或者是index.js。very good。我們解放了F5這個按鈕了。
其實,這個只是grunt.js的一個小功能,grunt.js強大得很,這裡先挖個坑,後續會和大家分享grunt.js的其他模組和更加詳細的Gruntfile.js的配置
再探 butterfly.js - grunt.js篇(一)