前端自动化之gulp
前题:1.安装好nodejs环境,或者nvm
2.安装npm包管理工具
简介:
可以自动的将开发阶段的代码进行压缩、合并、编译、加密等处理,生成项目提交的代码。
使用:
gulpfile.js文件编写的api较少,只有5个,可查看api自行编写。
http://www.gulpjs.com.cn/docs/api/
用npm下载gulp插件:
"browser-sync": "^2.18.13", "gulp-autoprefixer": "^4.0.0", "gulp-concat": "^2.6.1", "gulp-cssnano": "^2.1.2", "gulp-htmlmin": "^3.0.0", "gulp-less": "^3.3.2", "gulp-minify-css": "^1.2.4", "gulp-uglify": "^3.0.0"
编写gulp任务:
gulpfile.js文件案例:
'use strict';// 载入Gulp模块var gulp = require('gulp');var less = require('gulp-less');/*less编译*/var autoprefixer = require('gulp-autoprefixer');//给 CSS 增加前缀。解决某些CSS属性不是标准属性,有各种浏览器前缀的情况var cssnano = require('gulp-cssnano');var cssmin = require('gulp-minify-css');/*压缩css*/var concat = require('gulp-concat');/*合并*/var uglify = require('gulp-uglify');/*压缩混淆*/var htmlmin = require('gulp-htmlmin');/*html压缩*/var browserSync = require('browser-sync');/*网页自动刷新*/var reload = browserSync.reload;// 注册样式编译任务gulp.task('css', function() { gulp.src('src/css/*.css') .pipe(concat('main.css')) //合并css .pipe(gulp.dest('dist/css'))/*导出*/ .pipe(reload({ stream: true }));});// 注册脚本合并压缩任务gulp.task('script', function() { gulp.src('src/scripts/*.js') .pipe(concat('app.js')) .pipe(uglify()) .pipe(gulp.dest('dist/scripts')) .pipe(reload({ stream: true }));});gulp.task('image', function() {gulp.src('src/images/*.*') .pipe(gulp.dest('dist/images')) .pipe(reload({ stream: true }));});gulp.task('html', function() { gulp.src('src/*.html') .pipe(htmlmin({ collapseWhitespace: true, collapseBooleanAttributes: true, removeAttributeQuotes: true, removeComments: true, removeEmptyAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, })) .pipe(gulp.dest('dist')) .pipe(reload({ stream: true }));});gulp.task('serve', ['css', 'script', 'image', 'html'], function() { browserSync({ notify: false, port: 2015, server: { baseDir: ['dist'] } }); gulp.watch('src/styles*//*.css', ['css']); gulp.watch('src/scripts*//*.js', ['script']); gulp.watch('src/images*//*.*', ['image']); gulp.watch('src*//*.html', ['html']);});/*gulp.task('saaa', function() { console.log(1111111)});*/
可通过案例按照实际情况修改。