【Gulp】自動刪除上一次的編譯結果

node.js、npm、gulp、gulpfile、package.json、del

【Gulp】自動刪除上一次的編譯結果

node.js、npm、gulp、gulpfile、package.json、del


del

  1. 在專案中打開終端機安裝del套件(版本6.1.1)

1
$ npm install del@6.1.1


  1. 在gulpfile.js新增程式碼

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const gulp = require('gulp');
const del = require('del');

gulp.task('clean', function(){ 
  return del(['dist/**/*','!dist/img']) //刪除dist裡的所有檔案,圖片除外
});

gulp.task('copyHTML', function(){ 
  return gulp
    .src('src/*.html') 
    .pipe(gulp.dest('dist'))
});


  1. 在終端機執行指令

1
$ gulp clean


  1. 執行後會先執行刪除動作後,再重新生成新的index.html

you project
├─── node_modules/         
├─── dist/
│     │
│     └─── index.html   #刪除後再重新成的index.html
│ 
├─── src/
│     │
│     └─── index.html    
│
├─── gulpfile.js          
├─── package-lock.json    
└─── package.json   


  1. 回到gulpfile.js設定其他屬性
    • gitignore: 布林值,刪除時是否要保留版本控制的檔案
    • force: 布林值,檔案被其他程式佔用或是唯讀檔案是否強制刪除

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const gulp = require('gulp');
const del = require('del');

gulp.task('clean', function(){ 
  return del(['dist/**/*','!dist/img'],{
    gitignore: true, //保留git版控檔案
    force: true //強制刪除唯獨檔
  })
    .src('src/*.html') 
    .pipe(gulp.dest('dist')) 
});

gulp.task('copyHTML', function(){ 
  return gulp
    .src('src/**/*.html') 
    .pipe(gulp.dest('dist'))
});

gulp.task('default', gulp.series('copyHTML','clean'));


  1. 最後,在終端機執行gulp即可完成任務

1
$ gulp
gulp 

其他相關