僅作為拉勾前端筆記
Grunt基本使用
- 空項目中
yarn init --yes初始化package.json文件 - 為項目添加grunt 模塊
yarn add grunt - 創(chuàng)建gruntfile.js 作為Grunt的入口文件
// gruntfile.js
// 用于定義一些需要Grunt自動執(zhí)行的任務
// 需要導出一個函數(shù)
// 此函數(shù)接收一個 grunt 的形參,內(nèi)部提供一些創(chuàng)建任務時可以用到的API
module.exports = grunt =>{
grunt.registerTask('foo', ()=> {
console.log('hello grunt')
})
// yarn grunt foo 去執(zhí)行foo這個任務
grunt.registerTask('bar', '任務描述信息', ()=> {
console.log('hello grunt')
})
// bar 的第二個參數(shù)是字符串,作為任務的描述信息
grunt.registerTask('default', ['foo','bar'])
// 如果任務名為default, yarn grunt 會自動執(zhí)行這個任務,一般用default 去映射其他任務
// 傳遞數(shù)組會一次執(zhí)行數(shù)組中的函數(shù)
// grunt 默認支持同步函數(shù),如果需要調用異步函數(shù),需要用this.async的方式進行操作
grunt.registerTask('async-task', function(){
const done = this.async()
setTimeout(()=>{
console.log('async task working!')
done()
},1000)
})
}
Grunt標記任務失敗
- 構建任務的邏輯代碼中發(fā)生錯誤,比如文件找不到了,可以給這個任務標記為失敗的任務
- 通過在函數(shù)體內(nèi)
return false來實現(xiàn) - 前一個任務失敗后,后面的任務將不會被執(zhí)行
- 可以通過 yarn grunt default --force 設置為強制執(zhí)行
- 但是異步任務沒辦法直接return false 指定任務失敗,可以給異步函數(shù)給一個false 的實參去標記失敗
grunt.registerTask('async-task', function(){
const done = this.async()
setTimeout(()=>{
console.log('async task working!')
done(false)
},1000)
})
Grunt的配置方法
module.exports = grunt => {
grunt.initConfig({
foo:
})
grunt.registerTask('foo',()=>{
console.log(grunt.config('foo')) // 獲取配置中的foo的值
})
}
Grunt 多目標任務
module.exports = grunt => {
// 設置多目標任務的時候需要為任務配置不同的目標
// 下面的配置相當于為build任務配置了兩個目標,一個是css ,一個是js
grunt.initConfig({
build: {
// 在config中每個屬性的鍵都會作為一個目標,除了options以外,options會作為任務的配置選項出現(xiàn)
options: {
foo: 'bar'
},
css: {
options: {
foo: 'baz' // 目標內(nèi)設置的會覆蓋上級的options
},
},
js: '2'
}
})
// 多目標模式,可以讓任務根據(jù)配置形成多個子任務
grunt.registerMultiTask('build',function(){
console.log('build')
// 可以通過this拿到對應的數(shù)據(jù),
console,log(this.target,this.data,this.options)
})
}
Grunt 插件的使用
- 找到插件,通過npm 安裝到項目中
- 然后
grunt.loadNpmTasks加載插件中提供的task - 然后通過
grunt.initConfig中為插件提供配置選項
module.exports = grunt => {
// 以yarn add grunt-contrib-clean插件為例
// 如何配置去查對應包的使用文檔就好了
grunt.initConfig({
clean: {
temp: 'temp/app.js'
}
})
grunt.loadNpmTasks('grunt-contrib-clean')
}