前言:常見的自動化建構工具有Grunt , Gulp, FIS。Grunt 是最早的前端建構系統,但是會生成臨時檔案,有大量的磁盤讀寫的過程,建構速度比較慢。Gulp是目前最受歡迎的建構工具,對檔案的處理都是在記憶體中完成,還能預設執行多個任務,相對來說建構速度比較快,效率比較高。FIS是把常見的需求直接內建,操作簡單,友善,但不夠靈活。
接下來就談談grunt 的基本使用
一、基本同步的任務的執行
yarn init --yes
yarn add grunt
在檔案根目錄建立 gruntfile.js 作為grunt 的入口檔案。
// gruntfile.js 檔案
// 定義一些需要Grunt自動執行的任務,
// 需要導出一個函數
// 此函數接受一個Grunt 的形參,可沿用其提供的一寫api
module.exports = grunt =>{
grunt.registerTask ('foo',"任務描述",()=>{
console.log('hello grunt foo');
})
grunt.registerTask ('bar',"任務描述",()=>{
console.log('hello grunt bar');
})
grunt.registerTask ('default',['foo','bar'])
}
//運作指令:
yarn grunt "foo"
yarn grunt //預設執行grunt default 的任務
二、異步任務的執行
grunt 的操作是預設同步的模式,而異步任務的執行,需要調用this.async 得到一個回調函數,這個回調函數,要在你的異步操作執行結束後進行調用
// gruntfile.js 檔案
// 異步任務的執行
grunt.registerTask("async-task",function(){
const done = this.async()
setTimeout(()=>{
console.log('async task woring');
done()
},1000)
})
//運作指令
yarn grunt async-task 即可運作異步任務
三、标記任務的失敗。
直接在執行代碼内部rentrun false ,異步任務則在this.async 回調函數中輸入參數false ,即 done(false)。注意:失敗任務會阻塞後面的任務的執行。可以後面添加 --force 來強制執行
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TPn50dZpWT0smaOBDOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL4gjM3QjN0ETMxMzMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
四、多目标任務
Grunt 使用 registerMultiTask 來進行多目标任務,在使用多目标任務之前,需使用 initConfig 進行目标内容的配置,詳情如下
//gruntfile.js 檔案
// 多目标任務的執行
grunt.initConfig({
build:{
options:{ //配置選項參數,通過this.options() 擷取
foo:'123'
},
css:{ //配置具體的目标名稱,單獨檢視該目标可以使用 yarn grunt build:css 的方式運作
options:{
foo:'234' // 内部有配option 的資訊,則會覆寫最終 this.options 的輸出資訊
}
},
js:'567'
}
})
grunt.registerMultiTask('build',function(){
console.log(this.options());
console.log(`target:${this.target},data:${this.data}`);
})
//運作指令
yarn grunt build
五、grunt 常用插件使用及總結
sass , es6文法轉換,檔案監視。
yarn add grunt-sass sass
yarn add grunt-babel @babel/core @babel-preset-env --dev
yarn add load-grunt-tasks --dev
yarn add grunt-contrib-watch --dev