
var gutil = require('gulp-util');
gulp.task('default',function(){
gutil.log('message')
gutil.log(gutil.colors.red('error'))
gutil.log(gutil.colors.green('message')+'some')
})
这里强调以下,gulp操作必须进入到项目文件夹即node_modules文件夹所在界面才能在cmd窗口执行gulp操作。
4、怎样配置js文件
上面的写法有一个问题,只要有一个js文件被修改那么所有的js文件都会被重新编译。
我们只想编译被修改的文件怎么办?
使用gulp-watch-path
//引入模块:var watchPath = require('gulp-watch-path');//设置一个监听js文件的人物watchjsgulp.task('watchjs',function(){
gulp.watch('src/js/**/*.js',function(event){
var paths = watchPath('event','src/','dist/')//监听所有的js文件,有一个文件发生改变,则返回一个对象,该对象包含被修改js文件的相关属性。
/*
paths对象的结构如下:{srcPath:'src/js/log.js',
distPath:'dist/js/log.js',
distDir:'dist/js/',
srcFilename:'log.js',
distFilename:'log.js'}
*/
gulp.src(paths.srcPath)
.pipe( uglify())
.pipe(gulp.dest(paths.distDir))
})
})如果我们在编辑源码的时候出现格式错误,怎么输出这种错误?使用stream-combiner2
var handleError = function (err) {
var colors = gutil.colors;
console.log('\n')
gutil.log(colors.red('Error!'))
gutil.log('fileName: ' + colors.red(err.fileName))
gutil.log('lineNumber: ' + colors.red(err.lineNumber))
gutil.log('message: ' + err.message)
gutil.log('plugin: ' + colors.yellow(err.plugin))
}
var combiner = require('stream-combiner2')
gulp.task('watchjs', function () {
gulp.watch('src/js/**/*.js', function (event) {
var paths = watchPath(event, 'src/', 'dist/')
var combined = combiner.obj([
gulp.src(paths.srcPath),
uglify(),
gulp.dest(paths.distDir)
])
combined.on('error', handleError)
})
})压缩后的代码不存在换行符和空白符,导致出错后很难调试,好在我们可以使用 sourcemap 帮助调试
var sourcemaps = require('gulp-sourcemaps')
// ...
var combined = combiner.obj([
gulp.src(paths.srcPath),
sourcemaps.init(),
uglify(),
sourcemaps.write('./'),
gulp.dest(paths.distDir)
])
// ...此时 dist/js/ 中也会生成对应的 .map 文件,以便使用 Chrome 控制台调试代码
gulp-autoprefixer–解析 CSS 文件并且添加浏览器前缀到CSS规则里。在编译的时候会添加这些前缀
gulp.task('watchcss', function () {
gulp.watch('src/css/**/*.css', function (event) {
var paths = watchPath(event, 'src/', 'dist/')//用于检测被修改的文件,返回一个对像,该对象包含一些关于被修改文件的属性。
gulp.src(paths.srcPath)//获取文件地址
.pipe(sourcemaps.init())//初始化对象,便于后面生成该文件的.map文件
.pipe(autoprefixer({
browsers: 'last 2 versions'
}))//添加前缀
.pipe(minifycss())//执行压缩功能
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(paths.distDir))//相关推荐:
gulp的入门必知
