gulp小记

临时小项目需求,提升下开发速度(⇀‸↼‶)

npm install gulp -D

项目根目录创建gulpfile.js文件

引入gulp

const { src, dest, task, watch, series } = require('gulp');

使用html模板

这里用的Nunjucks

const nunjucks = require('gulp-nunjucks');
const removeEmptyLines = require('gulp-remove-empty-lines');

const gulpHtml = () =>
  src('src/page/*.html')
    .pipe(nunjucks.compile())
    .pipe(removeEmptyLines())
    .pipe(dest('dist/page'));

task('html', gulpHtml);

nunjucks中写循环或者判断的时候会产生比较多的空行,可以用removeEmptyLines移除

设置模板中的变量

src('src/page/*.html')
    .pipe(nunjucks.compile({ title: "hello 'world'"}))

不对变量进行转义

<title>{{ title | safe }}</title>

编译ES6

const babel = require('gulp-babel');

const gulpEs = () =>
  src('src/resource/js/*.es6')
    .pipe(
      babel({
        presets: ['@babel/preset-env']
      })
    )
    .pipe(dest('dist/resource/js'));

task('es', gulpEs);

使用SASS

const autoprefixer = require('gulp-autoprefixer');
const sass = require('gulp-sass');
sass.compiler = require('node-sass');

const gulpSass = () =>
  src('./src/resource/css/*.scss')
    .pipe(
      sass({
        outputStyle: 'compact'
      }).on('error', sass.logError)
    )
    .pipe(autoprefixer())
    .pipe(removeEmptyLines())
    .pipe(dest('dist/resource/css'));

task('sass', gulpSass);
  • autoprefixer用于补全浏览器私有前缀
  • 关于SASS文件的四种输出格式
/* expanded */
.class {
    margin: 0;
}

/* nested */
.class {
    margin: 0; }

/* compact */
.class { margin: 0; }
.class2 { padding: 0;}

/* compressed */
.class{margin:0;}.class2{padding:0;}

监听改变

task('watch', function () {
  watch('./src/resource/css/*.scss', gulpSass);
  watch('./src/resource/js/*.es6', gulpEs);
  watch('./src/page/*.html', gulpHtml);
});

多个task

task('build', series('taskName1', 'taskName2'));