Part2.3 Grunt

文章内容输出来源:拉勾教育大前端训练营

Grunt使用(有点类似plop)

  - yarn init -y  //新建项目
  - yarn add grunt //添加grunt
  - 项目根目录 新建gruntfile.js文件,定义grunt任务
  - yarn grunt 执行默认任务

  • 注意

    -  yarn grunt  xxx 执行registerTask注册过的指定任务
    
    -  任务中return false 表示任务失败,任务会中断
    
    -  异步任务中 done(false) 传递false实参表示失败的方法
    
    -  yarn grunt --force 执行default任务会忽略失败任务,全部执行
    
  • gruntfile.js

module.exports = grunt => {
    initConfig({
        build: {
            //任务配置项
            options:{
                foo:'bar'
            },
            css: 1,
            js: 2
        },
        foo:123
        
    })
    //多目标模式,可以让任务根据配置形成多个子任务
    grunt.registerMultiTask('build', function(){
        console.log('build task')
        console.log(this.options())
        console.log(`target:${this.target},data:${this.data}`)
    })

    grunt.registerTask('foo', () => {
        console.log('hello grunt')
    })
    grunt.registerTask('bar', () => {
        console.log('hello grunt')
    })
    grunt.registerTask('default', ['foo', 'bar','async-task'])
    grunt.registerTask('async-task', function () {
        const done = this.async()
        setTimeout(() => {
            console.log('async task')
            done()
        }, 1000);
    })
}
  - initConfig 配置项,接收对象作为参数,对象中的值可以是对象,也可以是个某个值.

  - 注册任务的名字跟配置中对象的名称相同可以直接获取到配置项中的值

  - 配置项中的每个task都可以有options配置项

  - 每个task中的子任务也可以拥有options配置项,执行的时候会覆盖公共的任务配置项

  - 通过this.config(xxx)获取到initConfig中的值     

grunt.registerMultiTask 多目标模式,可以让任务根据配置形成多个子任务

grunt 插件使用

  • 找到插件 add到项目中, loadNpmTasks 启动插件,根据插件文档配置 initConfig 任务选项, yarn grunt xxx(TaskName) 开始任务.

  • grunt的插件命名规范一般都是grunt-contrib-xxx

    - yarn add grunt-contrib-clean --dev 添加到项目中
    - initConfig({ 
          clean: {
                temp: 'temp/app.js' //配置目标 temp/** ; temp/*.txt
          }
       })
    - grunt loadNpmTasks('grunt-contrib-clean')
原文地址:https://www.cnblogs.com/zhuzy/p/13438744.html