基于gulp構(gòu)建一個工作流

實現(xiàn)前


實現(xiàn)之前惋增,我們先來了解下 gulp 自動構(gòu)建工具的具體流程

  1. 具體工作流程可以簡化為
    讀取文件流 --> 轉(zhuǎn)化流文件 --> 寫入流文件
  1. 完整的實現(xiàn)流程如下
    • 確定需求医清,需要構(gòu)建的任務(wù)
    • 初始化項目 yarn init
    • 安裝項目依賴 yarn add --dev gulp | yarn add -g gulp
    • 在項目的根目錄下創(chuàng)建 gulpfile.js 文件
    • 在 gulpfile.js 中實現(xiàn)我們的任務(wù)
    • 導出需要使用的任務(wù) module.exports = {start, build, ...}
    • 根據(jù)團隊需求確定是否在 package.json 文件的 scripts 中構(gòu)建命令
    • 測試 gulp + symbolName || yarn + scriptsName
    • 輸出結(jié)果

工作流程圖markdown語法畫不出來,將就著看下

一、需求


  • yarn lint 用于處理 scripts & styles 文件的格式問題
  • yarn compile 用于生成對應(yīng)的 styles & scripts & pages 文件
  • yarn serve 用于app的 開發(fā)運行 對應(yīng)的配置傳入 open port
  • yarn build 用于打包 對應(yīng)的配置傳入 production prod
  • yarn start 運行當前項目 生成環(huán)境 對應(yīng)的配置傳入 open port
  • yarn deploy 將當前文件推送到 github 的分支 默認 gh-pages
  • yarn clean 用于清除 dist temp 兩個目錄下的文件

二、按照需求定義相應(yīng)的任務(wù)

API說明見備注

  1. 初始化我們的項目
    • yarn init
    • 安裝 gulp 依賴 yarn add --dev gulp
    • 安裝 gulp 腳手架 yarn add -g gulp-cli 考慮到后續(xù)會多次使用
  2. 定義一個 lint 任務(wù)用于 實現(xiàn)對 js scss 代碼格式的校驗
    • 此處使用eslint stylelint 來校驗我們的代碼
    • 安裝相應(yīng)的依賴 yarn add --dev gulp-eslint gulp-stylelint stylelint stylelint-scss gulp-load-plugins
    • 安裝完依賴呢蛤,接下來來實現(xiàn)對應(yīng)的任務(wù)黑毅,以下為實現(xiàn)任務(wù)的代碼片段
      // 樣式校驗任務(wù) 需要在項目根目錄下 添加相應(yīng)的規(guī)則文件 .stylelintrc.json
      const lintStyles = () => {
          // dest() 寫入流文件 
          return src(config.paths.styles, {
              cwd: config.src
          }).pipe(plugins.stylelint())
      }
      // js校驗任務(wù) 需要在項目根目錄下 添加相應(yīng)的規(guī)則文件 .eslintrc.json
      const lintScripts = () => {
      return src(config.paths.scripts, {
              base: config.src,
              cwd: config.src
          }).pipe(plugins.eslint())
          .pipe(plugins.eslint.format())
          .pipe(plugins.eslint.failAfterError())
      }
      // 因為兩個任務(wù)可以并行執(zhí)行 所有選擇 parallel
      const lint = parallel(lintStyles, lintScripts)
      
    • scripts配置對應(yīng)的命令 lint: gulp lint運行對應(yīng)的命令 yarn lint 校驗是否如預(yù)期的效果一樣
      校驗正常
校驗異常
  1. 定義一個 compile 任務(wù) 用于處理 html | js | scss 文件灶体,并打包到 temp 文件下

    • 重復(fù)流程
    • 安裝需要用到的依賴 yarn add --dev gulp-sass gulp-babel @babel/preset-env gulp-swig browser-sync
    • 定義一個 pages 任務(wù)用于對 html 文件的處理;定義一個 scripts 任務(wù)用于對 js 文件的處理蝎抽;定義一個 styles 任務(wù)用于對 scss 文件的處理轉(zhuǎn)換;其次通過 parallel 構(gòu)建 gulp compile 命令, 最后配置對應(yīng)的 scripts 任務(wù)即可樟结;以下為實現(xiàn)任務(wù)的代碼片段
    const pages = () => {
    return src(config.paths.pages, {
        cwd: config.src, 
        ignore: ['{layouts,partials}/**']
    })
    // 將 data 數(shù)據(jù)渲染到 html 模板中
    .pipe(plugins.swig(data))
    .pipe(dest(config.temp))
    }
    
    const scripts = () => {
    return src(config.paths.scripts, {
        base: config.src,
        cwd: config.src, 
        sourcemaps: !isProd
    })
    .pipe(plugins.babel({presets: [require('@babel/preset-env')]}))
    .pipe(dest(config.temp, { sourcemaps: '.' }))
    // 如果 流文件 有變動 刷新當前的 頁面
    .pipe(bs.reload({stream: true}))
    }
    
    const styles = () => {
    return src(config.paths.styles, {
        base: config.src,
        cwd: config.src, 
        sourcemaps: !isProd
    })
    .pipe(plugins.sass())
    .pipe(dest(config.temp, { sourcemaps: '.' }))
    .pipe(bs.reload({stream: true}))
    }
    
    const compile = parallel(pages, scripts, styles)
    
    • 測試 yarn compile
  2. 為了便于調(diào)試精算,優(yōu)先實現(xiàn) yarn clean 命令用于刪除生成的緩存文件

    • 重復(fù)流程,安裝 del 依賴,用于刪除對應(yīng)的文件
    • 具體實現(xiàn)代碼如下
    const clean = () => {
        return del([config.temp, config.dist])
    }
    
    • 導出 clean 命令灰羽,測試 yarn clean
  3. 定義一個 serve 任務(wù) 用于開發(fā)調(diào)試使用 可傳入?yún)?shù) --port 端口號 --open 布爾值

    • 重復(fù)流程,安裝 minimist 依賴 用于處理 node 命令將 --open --port 轉(zhuǎn)換為參數(shù)
    • 具體實現(xiàn)代碼如下
    const argv = minimist(process.argv.slice(2))
    const devServe = () => {
        watch(config.paths.pages, {cwd: config.src}, pages)
        watch(config.paths.scripts, {cwd: config.src}, scripts)
        watch(config.paths.styles, {cwd: config.src}, styles)
    
        watch([
            config.paths.images, 
            config.paths.fonts
        ], 
        {cwd: config.src}, 
        bs.reload
        )
        watch('**', {cwd: config.public}, bs.reload)
        bs.init({
            notify: false,
            open: argv.open ? true : false,
            port: argv.port ? argv.port : 2080,
            plugins: [`bs-html-injector?files[]=${config.temp}/*.html`],
            server: {
                baseDir: [config.temp, config.src, config.public], // 'dist',
                // 優(yōu)先級高于 baseDir,路由映射 使用useref解決對應(yīng)的打包問題
                routes: {
                    '/node_modules': 'node_modules'
                }
            }
        })
    }
    
    const compile = parallel(pages, scripts, styles)
    const serve = series(compile, devServe)
    
    • 測試功能 yarn serve | year serve --port 8088 --open true
  4. 定義一個 build 任務(wù)玫镐,用于對 我們即將要發(fā)布的 文件進行 打包壓縮 可傳入傳輸 --prod --production

    • 重復(fù)流程,安裝 gulp-uglify gulp-html gulp-clean-css gulp-imagemin gulp-size gulp-if 等依賴,用于壓縮對應(yīng)的 js & html & css & images & fonts 等文件的壓縮
    const isProd = process.env.NODE_ENV
        ? process.env.NODE_ENV === 'production'
        : argv.production || argv.prod || false
    
    const images = () => {
        return src(config.paths.images, {
            base: config.src,
            cwd: config.src
        })
        .pipe(plugins.imagemin())
        .pipe(dest(config.dist))
    }
    
    const fonts = () => {
        return src(config.paths.fonts, {
            base: config.src,
            cwd: config.src
        })
        .pipe(plugins.imagemin())
        .pipe(dest(config.dist))
    }
    
    const extra = () => {
        return src('**', {
            base: config.public,
            cwd: config.public
        })
        .pipe(dest(config.dist))
    }
    
    const measure = () => {
        return src('**', { cwd: config.dest })
        .pipe(plugins.size({ gzip: true }))
    }
    
    const useref = () => {
        return src(config.paths.pages, {base: config.temp, cwd: config.temp})
            .pipe(plugins.useref({searchPath: [config.temp, '.']}))
            .pipe(plugins.if(/\.js$/, plugins.uglify()))
            .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
            .pipe(plugins.if(/\.html$/, 
                plugins.html(
                {
                    indent_size: 2, 
                    max_preserve_newlines: 1
                }
            )))
            .pipe(dest(config.dist))
    }
    
    const compile = parallel(pages, scripts, styles)
    const build = series(
        clean, 
        parallel(
            series(compile, useref), 
            fonts, 
            images, 
            extra
        ), 
        measure
    )
    
    • 測試功能 yarn build | year build --prod | year build --production
  5. 構(gòu)建一個 start 任務(wù)恐似, 運行當前項目生成環(huán)境 對應(yīng)的配置傳入 --open 布爾值 --port 端口號

    • 重復(fù)流程具體實現(xiàn)代碼如下:
        const prodServe = () => {
            bs.init({
                notify: false,
                open: argv.open ? true : false,
                port: argv.port ? argv.port : 2080,
                server: config.dist
            })
        }
    
        const build = series(
            clean, 
            parallel(
                series(compile, useref), 
                fonts, 
                images, 
                extra
            ), 
            measure
        )
    
        const start = series(build, prodServe)
    
    • 測試功能 yarn start | year start --port 8088 --open true
  6. 構(gòu)建一個 deploy 任務(wù)傍念,將當前文件推送到 github 的分支 默認 gh-pages

    • 重復(fù)流程,安裝項目依賴 gulp-gh-pages 具體實現(xiàn)代碼如下:
        const push = () => {
            return src('**', {cwd: config.dist})
            .pipe(plugins.ghPages({
                // 提交到 github 的分支名稱
                branch: argv.branch ? argv.branch : 'gh-pages',
                // 本地構(gòu)建的緩存目錄
                cacheDir: `${config.temp}/publish`
            }))
        }
    
    • 測試功能 yarn deploy

到此捂寿,我們就完成了一個gulp腳手架的構(gòu)建任務(wù)了

備注


src()


屬性 作用
globs 返回一個可以在管道中使用的流
options 配置文件的詳細說明

options

屬性 作用
base 在流文件中設(shè)置對應(yīng)的屬性
cwd 與相對路徑結(jié)合形成絕對路徑
sourcemaps 加載內(nèi)部sourcemaps 解析外部的sourcemaps
ignore 從匹配中排除對應(yīng)的文件

pipe 轉(zhuǎn)換對應(yīng)的流文件

dest()


屬性 作用
directory 將文件寫入的輸出目錄的路徑
options 配置文件的詳細說明

options

屬性 作用
cwd 與相對路徑結(jié)合形成絕對路徑
overwrite 是否覆蓋相同路徑的文件 default:true
sourcemaps 將內(nèi)部sourcemaps寫入輸出文件 外部sourcemaps

watch()


監(jiān)聽globs并在發(fā)生更改時運行任務(wù),任務(wù)與任務(wù)系統(tǒng)的其余部分被統(tǒng)一處理

屬性 作用
globs 用來監(jiān)聽文件系統(tǒng)
options 配置文件的詳細說明
task 一個任務(wù)函數(shù)

more api

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末孵运,一起剝皮案震驚了整個濱河市秦陋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌治笨,老刑警劉巖驳概,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異旷赖,居然都是意外死亡顺又,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進店門等孵,熙熙樓的掌柜王于貴愁眉苦臉地迎上來稚照,“玉大人,你說我怎么就攤上這事」迹” “怎么了上枕?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長弱恒。 經(jīng)常有香客問我辨萍,道長,這世上最難降的妖魔是什么返弹? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任锈玉,我火速辦了婚禮,結(jié)果婚禮上义起,老公的妹妹穿的比我還像新娘拉背。我一直安慰自己,他們只是感情好并扇,可當我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布去团。 她就那樣靜靜地躺著,像睡著了一般穷蛹。 火紅的嫁衣襯著肌膚如雪土陪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天肴熏,我揣著相機與錄音鬼雀,去河邊找鬼。 笑死蛙吏,一個胖子當著我的面吹牛源哩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播鸦做,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼励烦,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了泼诱?” 一聲冷哼從身側(cè)響起坛掠,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎屉栓,沒想到半個月后耸袜,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡域滥,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年骗绕,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片荆忍。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡刹枉,死狀恐怖微宝,靈堂內(nèi)的尸體忽然破棺而出虎眨,到底是詐尸還是另有隱情,我是刑警寧澤岳守,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布碌冶,位于F島的核電站,受9級特大地震影響譬重,放射性物質(zhì)發(fā)生泄漏罐氨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一以现、第九天 我趴在偏房一處隱蔽的房頂上張望约啊。 院中可真熱鬧恰矩,春花似錦、人聲如沸外傅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽技竟。三九已至,卻和暖如春熙尉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背检痰。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工铅歼, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留换可,地道東北人。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓俭识,卻偏偏與公主長得像洞渔,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子堤瘤,可洞房花燭夜當晚...
    茶點故事閱讀 44,901評論 2 355