利益于Babel轉(zhuǎn)換器捞烟,gulp 3.9及之后的版本我們可以在gulp文件中使用ES6(ES2015)
首先確保你的CLI和gulp版本至少是3.9:
gulp -v
CLI version 3.9.1
Local version 3.9.1
創(chuàng)建一個(gè) ES6 gulpfile
為了使用ES6 你需要使用Babel(確保你至少有Babel 6)作為你項(xiàng)目的依賴以及ES2015插件預(yù)置:
npm install babel-core babel-preset-es2015 --save-dev
接下來我們創(chuàng)建一個(gè).babelrc配置文件來啟用ES2015預(yù)設(shè):
touch .babelrc
然后在文件中增加以下內(nèi)容:
{
"presets": ["es2015"]
}
我們需要指示gulp使用Bable题画。為此德频,我需要將gulpfile.js重命名為gulpfile.babel.js
mv gulpfile.js gulpfile.babel.js
我們現(xiàn)在可以通過Babel使用ES6了,下面是在常用gulp任務(wù)中使用新的ES6功能的一個(gè)例子:
'use strict'
import gulp from 'gulp';
import sass from 'gulp-sass';
import autoprefixer from 'gulp-autoprefixer';
import sourcemaps from 'gulp-sourcemaps';
const dirs = {
src: 'src',
dest: 'build'
};
const sassPaths = {
src: `${dirs.src}/app.scss`,
dest: `${dirs.dest}/styles/`
};
gulp.task('styles', () => {
return gulp.src(paths.src)
.pipe(sourcemaps.init())
.pipe(sass.sync().on('error', plugins.sass.logError))
.pipe(autoprefixer())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.dest));
});
這里我們使用了ES6導(dǎo)入/模塊竞思,箭頭函數(shù)钞护,模板字符串和常量。