【Gulp】將javascript整合成穩定版本

node.js、npm、gulp、gulpfile、package.json、gulp-babel、@babel/core、@babel/preset-env

【Gulp】將javascript整合成穩定版本

node.js、npm、gulp、gulpfile、package.json、gulp-babel、@babel/core、@babel/preset-env


gulp-babel

  1. 在專案中打開終端機安裝gulp-babel@babel/core@babel/preset-env套件

1
$ npm install gulp-babel @babel/core @babel/preset-env

@開頭的套件,表示這是一個由特定組織或作者維護的套件


  1. 在gulpfile.js新增程式碼

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

gulp.task('babel', function(){
  return gulp
    .src('src/js/*.js') //引用js檔案來源
    .pipe(
      babel({  //使用babel套件
        presets:['@babel/env'] //設定使用'@babel/env'套件進行編譯
      })
    )  
    .pipe(gulp.dest('dist/js')) //js編譯完成路徑
});


  1. 在終端機執行指令

1
$ gulp babel


  1. 執行結果會將src裡的所有js檔(ES5、ES6、ES7)編譯,生成到dist裡變成穩定的all.js

you project
├─── node_modules/        
├─── dist/
│     │
│     └─── js/
│           │
│           └─── all.js   #編譯完成的js檔
│   
├─── src/
│     └─── js/
│           │
│           └─── all.js   #開發時編輯用的js檔
│     
├─── gulpfile.js          
├─── package-lock.json    
└─── package.json  


  1. 回到index.html引入js

1
2
3
<body>
    <script src="js/all.js"></script>
</body>


  1. 回到gulpfile.js設置屬性
    • minified: 布林值,是否要壓縮代碼

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

gulp.task('babel', function(){
  return gulp
    .src('src/js/*.js') 
    .pipe(
      babel({
        presets:['@babel/env'],
        minified: true //壓縮代碼
      })
    )  
    .pipe(gulp.dest('dist/js')) 
});

gulp.task('default', gulp.series('babel'));


  1. 【補充】安裝gulp-plumber編譯發生錯誤時,將訊息傳到控制台

1
$ npm install gulp-plumber

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

gulp.task('babel', function(){
  return gulp
    .src('src/js/*.js') 
    .pipe(plumber())
    .pipe(
      babel({
        presets:['@babel/env'],
        minified: true //壓縮代碼
      })
    )  
    .pipe(gulp.dest('dist/js')) 
});

gulp.task('default', gulp.series('babel'));


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

1
$ gulp
gulp 

其他相關