Grunt的基本操作

2020-11-19  本文已影响0人  yapingXu

仅作为拉勾前端笔记

Grunt基本使用

// gruntfile.js
// 用于定义一些需要Grunt自动执行的任务
// 需要导出一个函数
// 此函数接收一个 grunt 的形参,内部提供一些创建任务时可以用到的API
module.exports = grunt =>{
  grunt.registerTask('foo', ()=> {
    console.log('hello grunt')
  })
  // yarn grunt foo 去执行foo这个任务
  
  grunt.registerTask('bar', '任务描述信息', ()=> {
    console.log('hello grunt')
  })
  // bar 的第二个参数是字符串,作为任务的描述信息
  
  grunt.registerTask('default', ['foo','bar'])
  // 如果任务名为default, yarn grunt 会自动执行这个任务,一般用default 去映射其他任务
  // 传递数组会一次执行数组中的函数
  
  // grunt 默认支持同步函数,如果需要调用异步函数,需要用this.async的方式进行操作
  grunt.registerTask('async-task', function(){
    const done = this.async()
    setTimeout(()=>{
      console.log('async task working!')
      done()
    },1000)
  })
}

Grunt标记任务失败

  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会作为任务的配置选项出现
       options: {
         foo: 'bar'
       },
       css: {
         options: {
           foo: 'baz' // 目标内设置的会覆盖上级的options
         },
       },
       js: '2'
     }
   })
  
  // 多目标模式,可以让任务根据配置形成多个子任务
  grunt.registerMultiTask('build',function(){
    console.log('build')
    // 可以通过this拿到对应的数据,
    console,log(this.target,this.data,this.options)
  })
}

Grunt 插件的使用

module.exports = grunt => {
  // 以yarn add grunt-contrib-clean插件为例
  // 如何配置去查对应包的使用文档就好了
  grunt.initConfig({
    clean: {
      temp: 'temp/app.js'
    }
  })
  grunt.loadNpmTasks('grunt-contrib-clean')
  
}
上一篇 下一篇

猜你喜欢

热点阅读