Installation and use of front-end automation tool gulp

1. What is gulp

Gulp is a tool for building code in the front-end development process, and it is a powerful tool for building automation projects; it can not only optimize website resources, but also many repetitive tasks can be automatically completed with the correct tools during the development process; using it, we Not only can you write code happily, but also greatly improve our work efficiency. Through the strategy of code over configuration, Gulp makes simple tasks simple and complex tasks manageable.

2. Initialize a project

Create a folder named testGulp (call it whatever you want) and open it in the command line tool. implement

npm init

Then you can configure it yourself, as shown in the figure, and
insert image description here
finally just press Enter.

3. Installation of gulp

First of all, to use gulp, you must first install node, because npm follows node's package installation management tool. The specific download is directly from the Baidu nodejs Chinese website, and there is not much introduction here.
First install gulp globally in bold style:

npm install -g gulp

After installing gulp globally, you also need to install it once in each project that will use gulp. Change the directory to your project folder, and then execute on the command line:

npm install gulp

If you want to write gulp into the dependencies of the project package.json file during installation, you can add –save-dev:

npm install --save-dev gulp

This completes the gulp installation. As for why gulp needs to be installed locally in the project after installing gulp globally, if you are interested, you can read the answer made by someone on stackoverflow, which is generally for the flexibility of the version, but if you don’t understand it, don’t worry too much about it Question, just need to know that usually that's what we're going to do.

4. Start using Gulp

Building the gulpfile.js file
Gulp needs a file as its main file, in gulp this file is called gulpfile.js. Create a new file called gulpfile.js and put it in your project root directory. The next thing to do is to define our tasks in the gulpfile.js file. Below is an example of the simplest gulpfile.js file content, which defines a default task.

var gulp = require('gulp');
gulp.task('default',function(){
    console.log('hello world');
});

At this point our directory structure looks like this:

├── gulpfile.js
├── node_modules
│ └── gulp
└── package.json

//基本语法

gulp.task(“任务名称”,执行行数(){

return gulp.src(“操作的文件路径”).pipe(插件名【与var定义名字相同】){

相关参数

}))【可执行操作多个pipe()处理项】.pipe(gulp.dest(“返回结果的路径”))

});

Running the gulp task
To run the gulp task, just switch to the directory where the gulpfile.js file is stored (for Windows platforms, please use cmd or Power Shell, etc.), and then execute the gulp command on the command line.
Gulp can be followed by the name of the task to be executed, such as gulp task1, if no task name is specified, the default task named default will be executed.
For example, gulp minifycss executes a command to minify css
insert image description hereinsert image description here

5. Introduction to gulp's API

To use gulp, you only need to know 4 APIs: gulp.task(), gulp.src(), gulp.dest(), gulp.watch(), so it is easy to master, but there are a few places to understand To be thorough, I will explain them one by one below. In order to avoid misunderstandings, it is recommended to read the official documents first.

1 gulp.src()

In Gulp, the stream (stream) in Nodejs is used. First, the required stream is obtained, and then the stream can be imported to the place you want through the pipe() method of the stream, such as the Gulp plug-in, which is processed by the plug-in The final stream can continue to be imported into other plug-ins, and of course the stream can also be written into a file. So Gulp uses stream as the medium, and it does not need to generate temporary files frequently, which is one of the reasons why Gulp is fast. Back to the topic, the gulp.src() method is used to obtain the stream, but it should be noted that the content in this stream is not the original file stream, but a virtual file object stream (Vinyl files). This virtual file object The path, file name, content and other information of the original file are stored in . We don’t need to understand this in depth for the time being. You only need to simply understand that you can use this method to read the file you need to operate. Its syntax is:

gulp.src(globs[, options])

The globs parameter is a file matching pattern (similar to a regular expression), which is used to match file paths (including file names). Of course, a specific file path can also be directly specified here. When there are multiple matching patterns, this parameter can be an array.
options is an optional parameter. Normally we don't need to use it.

Let's focus on the glob matching rules used by Gulp and some file matching techniques.
Gulp internally uses the node-glob module for its file matching functionality. We can use the following special characters to match the files we want:

* 匹配文件路径中的0个或多个字符,但不会匹配路径分隔符,除非路径分隔符出现在末尾
** 匹配路径中的0个或多个目录及其子目录,需要单独出现,即它左右不能有其他东西了。如果出现在末尾,也能匹配文件。
? 匹配文件路径中的一个字符(不会匹配路径分隔符)
[...] 匹配方括号中出现的字符中的任意一个,当方括号中第一个字符为^或!时,则表示不匹配方括号中出现的其他字符中的任意一个,类似js正则表达式中的用法
!(pattern|pattern|pattern) 匹配任何与括号中给定的任一模式都不匹配的
?(pattern|pattern|pattern) 匹配括号中给定的任一模式0次或1次,类似于js正则中的(pattern|pattern|pattern)?
+(pattern|pattern|pattern) 匹配括号中给定的任一模式至少1次,类似于js正则中的(pattern|pattern|pattern)+
*(pattern|pattern|pattern) 匹配括号中给定的任一模式0次或多次,类似于js正则中的(pattern|pattern|pattern)*
@(pattern|pattern|pattern) 匹配括号中给定的任一模式1次,类似于js正则中的(pattern|pattern|pattern)

Let's take a series of examples to deepen the understanding

* 能匹配 a.js,x.y,abc,abc/,但不能匹配a/b.js
*.* 能匹配 a.js,style.css,a.b,x.y
*/*/*.js 能匹配 a/b/c.js,x/y/z.js,不能匹配a/b.js,a/b/c/d.js
** 能匹配 abc,a/b.js,a/b/c.js,x/y/z,x/y/z/a.b,能用来匹配所有的目录和文件
**/*.js 能匹配 foo.js,a/foo.js,a/b/foo.js,a/b/c/foo.js
a/**/z 能匹配 a/z,a/b/z,a/b/c/z,a/d/g/h/j/k/z
a/**b/z 能匹配 a/b/z,a/sb/z,但不能匹配a/x/sb/z,因为只有单**单独出现才能匹配多级目录
?.js 能匹配 a.js,b.js,c.js
a?? 能匹配 a.b,abc,但不能匹配ab/,因为它不会匹配路径分隔符
[xyz].js 只能匹配 x.js,y.js,z.js,不会匹配xy.js,xyz.js等,整个中括号只代表一个字符
[^xyz].js 能匹配 a.js,b.js,c.js等,不能匹配x.js,y.js,z.js
当有多种匹配模式时可以使用数组

//使用数组的方式来匹配多种文件
gulp.src(['js/*.js','css/*.css','*.html'])

Another advantage of using an array is that you can easily use the exclusion pattern, which is added before a single matching pattern in the array! That is, the exclusion pattern, which will exclude the match from the matching results. One thing to note is that you cannot Use an exclude pattern on the first element in the array

gulp.src([*.js,'!b*.js']) //匹配所有js文件,但排除掉以b开头的js文件
gulp.src(['!b*.js',*.js]) //不会排除任何文件,因为排除模式不能出现在数组的第一个元素中
此外,还可以使用展开模式。展开模式以花括号作为定界符,根据它里面的内容,会展开为多个模式,最后匹配的结果为所有展开的模式相加起来得到的结果。展开的例子如下:

a{b,c}d 会展开为 abd,acd
a{b,}c 会展开为 abc,ac
a{0..3}d 会展开为 a0d,a1d,a2d,a3d
a{b,c{d,e}f}g 会展开为 abg,acdfg,acefg
a{b,c}d{e,f}g 会展开为 abdeg,acdeg,abdeg,abdfg

2 gulp.dest()
gulp.dest() method is used to write files, its syntax is:

gulp.dest(path[,options])
path为写入文件的路径
options为一个可选的参数对象,通常我们不需要用到

If you want to use the gulp.dest() method well, you must understand the relationship between the path parameters passed in to it and the final generated file.
The usage process of gulp is generally like this: firstly, the file stream we want to process is obtained through the gulp. Then import it into gulp.dest() through the pipe method, and the gulp.dest() method writes the content in the stream to the file. The first thing to be clear here is that we pass in to gulp.dest() The path parameter can only be used to specify the directory of the file to be generated, but not the file name of the generated file. The file name of the generated file is the file name of the file stream imported into it, so the generated file name is Determined by the file stream imported into it, even if we pass it a path parameter with a file name, then it will treat the file name as a directory name, for example:

var gulp = require('gulp');
gulp.src('script/jquery.js')
    .pipe(gulp.dest('dist/foo.js'));
//最终生成的文件路径为 dist/foo.js/jquery.js,而不是dist/foo.js
要想改变文件名,可以使用插件gulp-rename

Let's talk about the relationship between the generated file path and the path parameter we pass in to the gulp.dest() method.
The file path generated by gulp.dest(path) is the part of the path where wildcards begin to appear in gulp.src() after the path parameter we passed in. For example:

var gulp = reruire('gulp');
//有通配符开始出现的那部分路径为 **/*.js
gulp.src('script/**/*.js')
    .pipe(gulp.dest('dist')); //最后生成的文件路径为 dist/**/*.js
//如果 **/*.js 匹配到的文件为 jquery/jquery.js ,则生成的文件路径为 dist/jquery/jquery.js

a little more example

gulp.src('script/avalon/avalon.js') //没有通配符出现的情况
    .pipe(gulp.dest('dist')); //最后生成的文件路径为 dist/avalon.js

//有通配符开始出现的那部分路径为 **/underscore.js
gulp.src('script/**/underscore.js')
    //假设匹配到的文件为script/util/underscore.js
    .pipe(gulp.dest('dist')); //则最后生成的文件路径为 dist/util/underscore.js

gulp.src('script/*') //有通配符出现的那部分路径为 *
    //假设匹配到的文件为script/zepto.js    
    .pipe(gulp.dest('dist')); //则最后生成的文件路径为 dist/zepto.js
通过指定gulp.src()方法配置参数中的base属性,我们可以更灵活的来改变gulp.dest()生成的文件路径。

When we do not configure the base attribute in the gulp.src() method, the default value of base is the part of the path before the wildcards begin to appear, for example:

gulp.src('app/src/**/*.css') //此时base的值为 app/src
上面我们说的gulp.dest()所生成的文件路径的规则,其实也可以理解成,用我们给gulp.dest()传入的路径替换掉gulp.src()中的base路径,最终得到生成文件的路径。

gulp.src('app/src/**/*.css') //此时base的值为app/src,也就是说它的base路径为app/src
     //设该模式匹配到了文件 app/src/css/normal.css
    .pipe(gulp.dest('dist')) //用dist替换掉base路径,最终得到 dist/css/normal.css
所以改变base路径后,gulp.dest()生成的文件路径也会改变

gulp.src(script/lib/*.js) //没有配置base参数,此时默认的base路径为script/lib
    //假设匹配到的文件为script/lib/jquery.js
    .pipe(gulp.dest('build')) //生成的文件路径为 build/jquery.js

gulp.src(script/lib/*.js, {base:'script'}) //配置了base参数,此时base路径为script
    //假设匹配到的文件为script/lib/jquery.js
    .pipe(gulp.dest('build')) //此时生成的文件路径为 build/lib/jquery.js    
用gulp.dest()把文件流写入文件后,文件流仍然可以继续使用。

3 gulp.task()
The gulp.task method is used to define tasks, and Orchestrator is used internally, and its syntax is:

gulp.task(name[, deps], fn)
name 为任务名
deps 是当前定义的任务需要依赖的其他任务,为一个数组。当前定义的任务会在所有依赖的任务执行完毕后才开始执行。如果没有依赖,则可省略这个参数
fn 为任务函数,我们把任务要执行的代码都写在里面。该参数也是可选的。

gulp.task('mytask', ['array', 'of', 'task', 'names'], function() { //定义一个有依赖的任务
  // Do something
});

The gulp.task() API has nothing to say, but you need to know how to control the order of task execution when executing multiple tasks.
Executing multiple tasks in gulp can be achieved through task dependencies. For example, if I want to execute three tasks, one, two, and three, then we can define an empty task, and then use those three tasks as dependencies of this empty task:

//只要执行default任务,就相当于把one,two,three这三个任务执行了
gulp.task('default',['one','two','three']);

If the tasks are not dependent on each other, the tasks will be executed in the order you wrote them. If there are dependencies, the dependent tasks will be executed first.
But if the task that a certain task depends on is asynchronous, you should pay attention, gulp will not wait for the asynchronous task that it depends on to complete, but will continue to execute subsequent tasks. For example:

gulp.task('one',function(){
  //one是一个异步执行的任务
  setTimeout(function(){
    console.log('one is done')
  },5000);
});

//two任务虽然依赖于one任务,但并不会等到one任务中的异步操作完成后再执行
gulp.task('two',['one'],function(){
  console.log('two is done');
});

In the above example, when we execute the two task, we will execute the one task first, but we will not wait for the asynchronous operation in the one task to complete before executing the two task, but execute the two task immediately. So the two task will be executed before the asynchronous operation in the one task is completed.

So if we want to wait for the asynchronous operation in the asynchronous task to complete before executing the subsequent task, what should we do?
There are three ways to achieve this:
First: After the asynchronous operation is completed, execute a callback function to notify gulp that the asynchronous task has been completed. This callback function is the first parameter of the task function.

gulp.task('one',function(cb){ //cb为任务函数提供的回调,用来通知任务已经完成
  //one是一个异步执行的任务
  setTimeout(function(){
    console.log('one is done');
    cb();  //执行回调,表示这个异步任务已经完成
  },5000);
});

//这时two任务会在one任务中的异步操作完成后再执行
gulp.task('two',['one'],function(){
  console.log('two is done');
});

Second: Return a stream object when defining a task. Applicable to the case where the task is to operate the stream obtained by gulp.src.

gulp.task('one',function(cb){
  var stream = gulp.src('client/**/*.js')
      .pipe(dosomething()) //dosomething()中有某些异步操作
      .pipe(gulp.dest('build'));
    return stream;
});

gulp.task('two',['one'],function(){
  console.log('two is done');
});

Third: return a promise object, for example

var Q = require('q'); //一个著名的异步处理的库 https://github.com/kriskowal/q
gulp.task('one',function(cb){
  var deferred = Q.defer();
  // 做一些异步操作
  setTimeout(function() {
     deferred.resolve();
  }, 5000);
  return deferred.promise;
});

gulp.task('two',['one'],function(){
  console.log('two is done');
});

That's all for gulp.task(), the main thing is to know what to do when the dependency is an asynchronous task.

4 gulp.watch()
gulp.watch() is used to monitor the changes of files. When the files change, we can use it to perform corresponding tasks, such as file compression. Its syntax is

gulp.watch(glob[, opts], tasks)
glob 为要监视的文件匹配模式,规则和用法与gulp.src()方法中的glob相同。
opts 为一个可选的配置对象,通常不需要用到
tasks 为文件变化后要执行的任务,为一个数组

gulp.task('uglify',function(){
  //do something
});
gulp.task('reload',function(){
  //do something
});
gulp.watch('js/**/*.js', ['uglify','reload']);
gulp.watch()还有另外一种使用方式:

gulp.watch(glob[, opts, cb])
glob和opts参数与第一种用法相同
cb参数为一个函数。每当监视的文件发生变化时,就会调用这个函数,并且会给它传入一个对象,该对象包含了文件变化的一些信息,type属性为变化的类型,可以是added,changed,deleted;path属性为发生变化的文件的路径

gulp.watch('js/**/*.js', function(event){
    console.log(event.type); //变化类型 added为新增,deleted为删除,changed为改变 
    console.log(event.path); //变化的文件的路径
}); 

Six, some commonly used gulp plug-ins

1. Automatically load plug-ins
Installation gulp-load-plugins
: npm install --save-dev gulp-load-plugins
To use gulp plug-ins, you requiremust load the plug-ins. If we want to use a lot of plug-ins, gulpfile.jsthe beginning of our file may look like this:

var gulp = require("gulp");//导入glup
var sass = require("gulp-sass");//拷贝并编译scss
var server = require("gulp-connect");//建立服务器
var concat = require("gulp-concat");//合并js文件
var uglify = require("gulp-uglify");//压缩js文件
var minifyCss = require("gulp-minify-css");压缩css
var imagemin = require("gulp-imagemin");压缩图片
var rename = require("gulp-rename");//文件重命名
var rev = require("gulp-rev");//给静态资源文件名添加一个哈希值后缀
var revCollector = require("gulp-rev-collector");//自动添加版本号
var autoprefixer = require("gulp-autoprefixer");//对css添加浏览器后缀
var htmlmin = require("gulp-htmlmin");//对html页面进行压缩
//更多的插件...
z = require('gulp-z');   

While there's nothing wrong with this, it can make our gulpfile.jsfiles very verbose and uncomfortable to look at. gulp-load-pluginsPlugins are designed to solve this problem.
gulp-load-pluginsThis plugin can automatically load the plugins package.jsonin the file for you gulp. package.jsonFor example, suppose your dependencies in your file look like this:

{
  "devDependencies": {
    "gulp": "~3.6.0",
    "gulp-rename": "~1.2.0",
    "gulp-ruby-sass": "~0.4.3",
    "gulp-load-plugins": "~0.5.1"
  }
}

Then we can gulpfile.js中使用gulp-load-plugins来load the plugin for us:

var gulp = require('gulp');
//加载gulp-load-plugins插件,并马上运行它
var $ = require('gulp-load-plugins')();

Then gulp-rename和gulp-ruby-sasswhen we want to use these two plug-ins, we can use $.renameand $.sassinstead, that is, the original plug-in name removes gulp-the prefix, and then converts it to camel case.
Essentially gulp-load-pluginsdoing the following conversion for us

$.rename = require('gulp-rename');
$.sass = require('gulp-ruby-sass');

gulp-load-pluginsIt does not load all the plug-ins in the beginning package.json, gulpbut only loads that plug-in when we need to use a certain plug-in.
The last thing to remind is that because the plugin gulp-load-pluginsis loaded through your package.jsonfile, you must ensure that the plugin you need to automatically load has been written into package.jsonthe file, and these plugins are already installed.

2. Delete files and folders
Installation: npm install --save-dev gulp del
The project directory is as follows:
insert image description here

	var del = require('del');
    gulp.task('clean:css', function (cb) {
      del([
     	 //根据路径删除dist文件夹下的css中的style.min.css文件
        'dist/css/style.min.css',
        // 这里我们使用一个通配模式来匹配 `css` 文件夹中的所有东西
	    'dist/css/**/*',
	    // 我们不希望删掉这个文件,所以我们取反这个匹配模式
	    '!dist/css/style.min.css'
      ], cb);
    });
    
    gulp.task('default', gulp.series('clean:css'));

3. Rename
the installation:npm install --save-dev gulp-rename

var minifycss = require('gulp-minify-css'); //引用插件,需npm install --save-dev gulp-minify-css
var rename = require("gulp-rename");//文件重命名
gulp.task('minifycss', function() {
	return gulp.src('src/css/style.css') //压缩的文件
		.pipe(minifycss()) //执行压缩
		.pipe(rename({extname:'.min.css'}))//将style的后缀名改为min.css
		.pipe(gulp.dest('dist/css')); //输出文件夹
});

or

  gulp.task('rename', function () {
        gulp.src('src/css/style.css')
        .pipe(uglify())  //压缩
        .pipe(rename('style.min.css')) //会将style.css重命名为style.min.css
        .pipe(gulp.dest('dist/css'));
        //关于gulp-rename的更多强大的用法请参考https://www.npmjs.com/package/gulp-rename
    });

4. Compress js files
Installation: npm install --save-dev gulp-uglify
used to compress js files, using the uglify engine

var gulp = require('gulp'),
    uglify = require("gulp-uglify");
 
gulp.task('minify-js', function () {
    gulp.src('js/*.js') // 要压缩的js文件
    .pipe(uglify())  //使用uglify进行压缩,更多配置请参考:
    .pipe(gulp.dest('dist/js')); //压缩后的路径
});

5. Compress css file
gulp-clean-css:压缩css文件(别用gulp-minify-css,已废弃)

installation:npm install --save-dev gulp-minify-css

var minifycss = require('gulp-minify-css'); 
gulp.task('minifycss', function() {
	return gulp.src('src/css/style.css')  要压缩的css文件
		.pipe(minifycss()) //执行压缩
		.pipe(gulp.dest('dist/css')); //输出文件夹
});

// Compress css and create a json file to automatically add the version number

var rev = require("gulp-rev");//给静态资源文件名添加一个哈希值后缀
gulp.task("css",function () {
    return gulp.src("src/css/*.css")     
    .pipe(minifycss()).pipe(rev())
    .pipe(gulp.dest("dist/css/"))
    .pipe(rev.manifest())
    .pipe(gulp.dest("dist/css/"));
});

6. Compressed html
installation:npm install --save-dev gulp-htmlmin

htmlmin = require('gulp-htmlmin');
 
gulp.task('htmlMin', function () {
    var options = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyjs: true,//压缩页面JS
        minifycss: true//压缩页面CSS
    };
    gulp.src('src/*.html')
        .pipe(htmlmin(options))
        .pipe(gulp.dest('dist'));
});

7. Compress picture
installation:npm install --save-dev gulp-imagemin

You can use the gulp-imagemin plugin to compress jpg, png, gif and other images.

var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant'); //png图片压缩插件

gulp.task('default', function () {
    return gulp.src('src/images/*')
        .pipe(imagemin({
            progressive: true,
            use: [pngquant()] //使用pngquant来压缩png图片
        }))
        .pipe(gulp.dest('dist'));
});

The use of gulp-imagemin is a bit more complicated, and it also has many plug-ins. It is recommended to go to its project home page to see the documentation

8. File merging
Use gulp-concat
installation: npm install --save-dev gulp-concat
used to merge multiple files into one file, we can use it to merge js or css files, etc., so that the number of http requests on the page can be reduced

var gulp = require('gulp'),
    concat = require("gulp-concat");
 
gulp.task('concat', function () {
    gulp.src('js/*.js')  //要合并的文件
    .pipe(concat('all.js'))  // 合并匹配到的js文件并命名为 "all.js"
    .pipe(gulp.dest('dist/js'));
});

Merge loading.js and toast.js into main.js and output to the dest/js directory

gulp.task('minifyjs', function() {
	return gulp.src(['src/js/loading.js','src/js/toast.js'])      //需要操作的文件
		.pipe(concat('main.js'))    //合并所有js到main.js
		.pipe(rename({suffix: '.min'}))   //rename压缩后的文件名
		.pipe(uglify())    //压缩
		.pipe(gulp.dest('dist/js'));  //输出
});

9. To compile less and sass,
use gulp-less to install:npm install --save-dev gulp-less

var gulp = require('gulp'),
    less = require("gulp-less");
 
gulp.task('compile-less', function () {
    gulp.src('less/*.less')
    .pipe(less())
    .pipe(gulp.dest('dist/css'));
});

Sass uses gulp-sass, install:npm install --save-dev gulp-sass

var gulp = require('gulp'),
    sass = require("gulp-sass");
 
gulp.task('compile-sass', function () {
    gulp.src('sass/*.sass')
    .pipe(sass())
    .pipe(gulp.dest('dist/css'));
});

10. Automatic refresh
Use the gulp-livereload plug-in,
install: npm install --save-dev gulp-livereload
when the code changes, it can help us automatically refresh the page.
This plug-in is best used with Google Chrome, and the livereload chrome extension extension plug-in needs to be installed. If you can’t download it, please FQ yourself .

var gulp = require('gulp'),
    less = require('gulp-less'),
    livereload = require('gulp-livereload');

gulp.task('less', function() {
  gulp.src('less/*.less')
    .pipe(less())
    .pipe(gulp.dest('css'))
    .pipe(livereload());
});

gulp.task('watch', function() {
  livereload.listen(); //要在这里调用listen()方法
  gulp.watch('less/*.less', ['less']);
});

11. js code check
Use gulp-jshint
to install: npm install --save-dev gulp-jshint
used to check js code

var gulp = require('gulp'),
    jshint = require("gulp-jshint");
 
gulp.task('jsLint', function () {
    gulp.src('js/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter()); // 输出检查结果
});

12. Batch copy

src/images/**/*Copy all resources under all files under images

gulp.task("copy-img",function () {
    return gulp.src("src/images/**/*")
    .pipe(imagemin())
    .pipe(gulp.dest("dist/images/"));
})

Multi-group copy and merge "!src/json/s-*.json"//Exclude json files starting with s

! filename means exclude

gulp.task("copy-data",function () {
    return gulp.src(["src/json/*","src/xml/*","!src/json/s-*.json"])
    .pipe(gulp.dest("dist/data/"));
})

12. Used to replace the link tag src path on the HTML page (easy to change the file name)

gulp.task("rev-collector",function () {
    return gulp.src(["dist/css/**/*.json","dist/index.html"])
    .pipe(revCollector({
        replaceReved:true,
    }))
    .pipe(gulp.dest("dist/"))
});

13. Multitasking at the same time

//gulp.task(“合并的任务名”,[“任务1”,”任务2”,”任务3”,...]);
gulp.task("default",["copyindex","copy-img","copy-data"]);

14. CSS automatically handles browser prefixes
such as adding -webkit- to solve browser compatibility issues

var autoprefixer = require('gulp-autoprefixer');
 
gulp.task('autoprefixer', function () {
    gulp.src('css/index.css')
        .pipe(autoprefixer())
        .pipe(gulp.dest('dist/css'));
});

15. Write the service

var open = require('open');
gulp.task('serve',['build'], function() {
    $.connect.server({
        //服务起来的入口
        root: [app.devPath],
        //文件更改后自动刷新页面
        livereload: true,
        //端口号
        port: 1234
    });
    // 在 命令工具中执行 gulp serve  就相当于是启动了服务
    //自动打开浏览器
    open('http://localhost:1234');
    //我们希望更改了文件,就自动编译,并且打包等然后打开浏览器
    gulp.watch('bower_components/**/*' , ['lib']);
    //监听 script 下边的 js 文件,并执行 script 方法
    gulp.watch(app.srcPath + 'script/**/*.js', ['script']);
    gulp.watch(app.srcPath + '**/*.html', ['html']);
    gulp.watch(app.srcPath + 'data/**/*.json', ['json']);
    gulp.watch(app.srcPath + 'style/**/*.less', ['less']);
    gulp.watch(app.srcPath + 'image/**/*', ['image']);
    //这样文件变更了就会自动构建
});

//Tasks executed by default, directly execute gulp to change the line. After all the writing is completed, execute gulp on the terminal.

gulp.task('default', ['serve']);

16. gulp-tmtsprite and gulp-spritesmith: sprite map

gulp-tmtsprite official website: https://www.npmjs.com/package/gulp-tmtsprite
gulp-spritesmith official website: https://www.npmjs.com/package/gulp-spritesmith
sprity official website: https://www.npmjs .com/package/sprity
Other: https://www.npmjs.com/search?q=gulp+sprite

不足之处,还望见谅并指正

Guess you like

Origin blog.csdn.net/qq_39327418/article/details/90906179
Recommended