動態

詳情 返回 返回

退出歷史舞台的Grunt基本瞭解 - 動態 詳情

Grunt

Grunt 生態系統非常龐大,並且一直在增長。由於擁有數量龐大的插件可供選擇,因此,你可以利用 Grunt 自動完成任何事,並且花費最少的代價。如果找不到你所需要的插件,那就自己動手創造一個 Grunt 插件,然後將其發佈到 npm 上吧

Grunt基本使用

yarn add grunt
yarn add安裝之後,創建一個gruntfile.js文件,這是grunt的入口文件,用於定義一些需要Grunt自動執行的人物,需要導出一個函數,此函數接收一個grunt的形參,內部提供一些創建任務時可以用到的API
例子如下:

module.exports = grunt => {
    grunt.registerTask('foo', () => { // yarn grunt foo 執行
        console.log('hello grunt') // hello grunt
    })

    grunt.registerTask('bar', "des", () => { // yarn grunt bar 執行
        console.log("another task") // another task
    })

    // grunt.registerTask('default',"des",()=>{  // 默認導出命令為default,yarn grunt就可以執行
    //     console.log("another task")
    // })
    grunt.registerTask("default", ["foo", "bar"]) // 會一次執行foo任務和bar任務

    // grunt.registerTask("async-task",()=>{  
    //     setTimeout(() => {
    //         console.log("async task ...")  // 異步任務,這裏不會有輸出
    //     }, 1000);
    // })

    grunt.registerTask("async-task", function () {
        const done = this.async() // grunt默認支持同步函數,如果需要異步操作,需要一個this.async()方法得到一個異步操作
        setTimeout(() => {
            console.log("async task. ")
            done() // 執行異步函數,標記完成
        }, 1000);
    })
}

標記任務失敗

    grunt.registerTask("bad", () => {
        console.log("bad working")
        return false // 返回false,,標記任務失敗
    })

    grunt.registerTask('foo', () => {
        console.log('hello grunt')
    })

    grunt.registerTask('bar', "des", () => {
        console.log("another task")
    })

    grunt.registerTask("default", ["foo", "bad", "bar"]) // bar不會執行

image.png
也可以在命令中加入--force繼續執行任務
yarn grunt --force
image.png
異步任務中標記任務失敗

    grunt.registerTask("async-task", function () {
        const done = this.async() 
        setTimeout(() => {
            console.log("async task. ")
            done(false) // 執行異步函數,標記false任務失敗
        }, 1000);
    })

配置方法

grunt有一個添加配置選項的api,initConfig

    grunt.initConfig({
        foo: 'bar' // foo為任務名
    })
    grunt.registerTask("foo", () => {
        console.log(grunt.config('foo'))  // 打印bar
    })

    grunt.initConfig({
        foo: { 
            bar: 123
        }
    })
    grunt.registerTask("foo", () => {
        console.log(grunt.config('foo.bar')) // 打印123
    })

多目標任務

可以理解為子任務

    grunt.initConfig({
        build: { // 為build任務添加兩個目標
            css: "1",
            js: '2'
        }
    })

    grunt.registerMultiTask('build', function () {
        console.log('build task')
    })

image.png
運行其中一個命令中用冒號隔開build:css
image.png

    grunt.initConfig({
        build: { // 為build任務添加兩個目標
            options: { // 任務配置選項
                foo: 'bar'
            },
            css: {
                options: {
                    foo: 'baz' // 下面的配置選項會覆蓋上面的配置選項
                }
            },
            js: '2'
        }
    })

    grunt.registerMultiTask('build', function () {
        console.log(this.options()) // 拿到任務的配置選項 
        console.log(`target:${this.target},data:${this.data}`)
    })

image.png

插件

使用插件步驟,安裝插件,引入插件,根據插件文檔使用插件
例子,使用grunt-contrib-clean插件

    grunt.initConfig({
        clean:{
            temp:'temp/app.js', // 可以執行任務名或者使用通配符通配一些文件
            // temp:'temp/*.txt' // 後綴為txt的全部清除
            // temp:"temp/**" // temp下文件全部清除
        }
    })
    // 例如清除temp目錄下的app.js
    grunt.loadNpmTasks('grunt-contrib-clean') // grunt插件命令格式大多數都是grunt-contrib-***,loadNpmTasks加載進來

一個監聽js,scss文件變化的基礎案例

    const sass = require('sass')
    const loadGruntTasks = require('load-grunt-tasks')
    grunt.initConfig({
        sass: { //  yarn add grunt-sass
            options: {
                sourceMap: true,
                implementation: sass
            },
            main: {
                files: {
                    'dist/css/main.css': "src/scss/mian.scss" // 分別為目標路徑和源路徑
                }
            }
        },
        babel: {  // 編譯es6
            options: {
                sourceMap: true,
                presets: [
                    '@babel/preset-env'
                ]
            },
            main: {
                files: {
                    'dist/js/app.js': "src/js/app.js"
                }
            }
        },
        watch: { // grunt-contrib-watch 監聽文件變化
            js: {
                files: ['src/js/*.js'],
                tasks: ["babel"]
            },
            css: {
                files: ['src/scss/*.scss'],
                tasks: ['sass']
            }
        }
    })

    // grunt.loadNpmTasks('grunt-sass')
    loadGruntTasks(grunt) // 會自動加載所有的grunt插件中的任務
    grunt.registerTask('default',['sass','babel','watch']) // 使用default, 確保sass,babel先編譯,再監聽
user avatar kobe_fans_zxc 頭像 dirackeeko 頭像 beckyyyy 頭像 heath_learning 頭像 lizhiqianduan 頭像 linong 頭像 qifengliao_5e7f5b20ee3bd 頭像 wanzuqiudeshangba 頭像 ailvyoudemaojin 頭像 tonyyoung 頭像 zcf0508 頭像 limingcan562 頭像
點贊 17 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.