javascript Gulp文件优化js,css和图像
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Gulp文件优化js,css和图像相关的知识,希望对你有一定的参考价值。
npm install gulp-concat gulp-uglify gulp-strip-debug gulp-autoprefixer gulp-minify-css gulp-changed gulp-imagemin gulp-jshint --save-dev
// include gulp
var gulp = require('gulp');
//jshint
var jshint = require('gulp-jshint');
var changed = require('gulp-changed');
//imgs
var imagemin = require('gulp-imagemin');
var minifyHTML = require('gulp-minify-html');
// js files
var concat = require('gulp-concat');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
// css files
var autoprefix = require('gulp-autoprefixer');
var minifyCSS = require('gulp-minify-css');
// JS hint task
gulp.task('jshint', function() {
gulp.src('./src/scripts/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// minify new images
gulp.task('imagemin', function() {
var imgSrc = './src/images/**/*',
imgDst = './build/images';
gulp.src(imgSrc)
.pipe(changed(imgDst))
.pipe(imagemin())
.pipe(gulp.dest(imgDst));
});
// minify new or changed HTML pages
gulp.task('htmlpage', function() {
var htmlSrc = './src/*.html',
htmlDst = './build';
gulp.src(htmlSrc)
.pipe(changed(htmlDst))
.pipe(minifyHTML())
.pipe(gulp.dest(htmlDst));
});
// JS concat, strip debugging and minify
gulp.task('scripts', function() {
gulp.src(['./src/scripts/lib.js','./src/scripts/*.js'])
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./build/scripts/'));
});
// CSS concat, auto-prefix and minify
gulp.task('styles', function() {
gulp.src(['./src/styles/*.css'])
.pipe(concat('styles.css'))
.pipe(autoprefix('last 2 versions'))
.pipe(minifyCSS())
.pipe(gulp.dest('./build/styles/'));
});
// default gulp task
gulp.task('default', ['imagemin', 'htmlpage', 'scripts', 'styles'], function() {
// watch for HTML changes
gulp.watch('./src/*.html', function() {
gulp.run('htmlpage');
});
// watch for JS changes
gulp.watch('./src/scripts/*.js', function() {
gulp.run('jshint', 'scripts');
});
// watch for CSS changes
gulp.watch('./src/styles/*.css', function() {
gulp.run('styles');
});
});
以上是关于javascript Gulp文件优化js,css和图像的主要内容,如果未能解决你的问题,请参考以下文章
前端构建工具gulp之基本介绍
Gulp:静态资源(css,js)版本控制
Gulp应用场景
初探前端自动化神器 Gulp
Gulp 插件
Gulp4.0入门和实战