安装gulp到全局:npm install -g gulp安装gulp到某个项目:npm install --save gulp注意:请先安装nodejs(自带npm)
//在你的项目根目录下创建gulpfile.js,代码如下:// 引入 gulpvar gulp = require('gulp');// 引入组件var htmlmin = require('gulp-htmlmin'), //html压缩 imagemin = require('gulp-imagemin'),//图片压缩 pngcrush = require('imagemin-pngcrush'), minifyCSS = require('gulp-minify-css'),//css压缩 jshint = require('gulp-jshint'),//js检测 uglify = require('gulp-uglify'),//js压缩 concat = require('gulp-concat'),//文件合并 rename = require('gulp-rename'),//文件更名 notify = require('gulp-notify');//提示信息// 压缩htmlgulp.task('html', function() { return gulp.src('src/*.html') .pipe(htmlmin({collapseWhitespace: true})) .pipe(gulp.dest('./dest')) .pipe(notify({ message: 'html task ok' }));});// 压缩图片gulp.task('img', function() { return gulp.src('src/images/*') .pipe(imagemin({ PRogressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngcrush()] })) .pipe(gulp.dest('./dest/images/')) .pipe(notify({ message: 'img task ok' }));});// 合并、压缩、重命名cssgulp.task('css', function() { return gulp.src('src/css/*.css') .pipe(concat('main.css')) .pipe(gulp.dest('dest/css')) .pipe(rename({ suffix: '.min' })) .pipe(minifycss()) .pipe(gulp.dest('dest/css')) .pipe(notify({ message: 'css task ok' }));});// 检查jsgulp.task('lint', function() { return gulp.src('src/js/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(notify({ message: 'lint task ok' }));});// 合并、压缩js文件gulp.task('js', function() { return gulp.src('src/js/*.js') .pipe(concat('all.js')) .pipe(gulp.dest('dest/js')) .pipe(rename({ suffix: '.min' })) .pipe(uglify()) .pipe(gulp.dest('dest/js')) .pipe(notify({ message: 'js task ok' }));});// 默认任务gulp.task('default', function(){ gulp.run('img', 'css', 'lint', 'js', 'html'); // 监听html文件变化 gulp.watch('src/*.html', function(){ gulp.run('html'); }); // Watch .css files gulp.watch('src/css/*.css', ['css']); // Watch .js files gulp.watch('src/js/*.js', ['lint', 'js']); // Watch image files gulp.watch('src/images/*', ['img']);});
//如上gulpfile.js安装依赖如下,cd切换到你的项目下然后:npm install gulp-htmlmin gulp-imagemin imagemin-pngcrush gulp-minify-css gulp-jshint gulp-uglify gulp-concat gulp-rename gulp-notify --save-dev
恭喜你,你已经学会使用gulp了,例如:执行默认任务: gulp, 合并压缩css: gulp css
gulp官网:http://gulpjs.com/
gulp插件:http://gulpjs.com/plugins/
新闻热点
疑难解答