Gulp- build tool organize related content

Gulp- Profile

Automate and enhance your workflow | automated build tools to enhance your workflow

What Gulp that?

gulp is a process of constructing a front-end development tool based on the code flow automation project is to build a weapon; it can not only optimize the website resources, but also in the development process, many repetitive tasks can use the right tools to automate;
use it not only very pleasant to write code, but also greatly improve our efficiency.

gulp is based Nodejs automated task runner, it can automate the complete javascript, test coffee, sass, less, html / image, css and other documents, inspection, consolidation, compression, formatting, auto-refresh browser, the deployment file generation , repeat these steps and monitor file specified after the changes. On realization, she draws on the Unix operating system pipe (pipe) thought, the output of the previous stage, directly into the input stage, makes it very simple in operation. In this article, we will learn how to use Gulp to change the development process, enabling developers to more quickly and efficiently.

gulp and grunt is very similar, but frequently IO operations compared to the grunt of, gulp stream operations, can more easily build work done faster.

Gulp core concepts?

Stream is simply to establish the tool directed to an object based on processing data abstraction. In the stream, defined the basic operation of some data processing, such as reading data, writing data, the programmer is the stream of all operations, without concern for the other end of the flow of real data stream. Not only can process stream file, various data formats can also process dynamic memory, network data.

And gulp it is to try to simplify the task of writing work through policy and code stream over configuration. It looks a bit "like jQuery" approach to string together to create action build tasks. Back in the early Unix, the flow has existed. Node.js stream ecosystems also play an important role, similar to the * nix almost all device abstraction for files like, Node almost all IO operations have become a stream of abstract operation. So write with a gulp task can also be seen as a task to write Node.js. When the stream, gulp removes the intermediate files, only the final output is written to disk, and therefore the whole process faster.

Gulp features?

  • Ease of use:
    through code policy configuration is superior to, gulp make simple tasks simple and complex tasks manageable.
  • Build fast:
    use the power of Node.js stream, you can quickly build the project and reduce the frequency of IO operations.
  • Easy to learn:
    with minimal API, master gulp effortlessly, building work under control: as a series of flow pipe.
  • Plug quality:
    GULP strict guidelines to ensure that the plug-quality plug-ins have to work as simple as you would expect.

Gulp- environment to build

gulpIs based on the nodeachieved, then we need to first install node.

Node is based on Google V8 JavaScripta platform built engine, it can take advantage of Web services, PHP do similar things.

npm install -g gulp  # 全局安装gulp 
gulp -v  # 查看gulp是否安装成功

➜  ~ gulp -v
   [20:17:32] CLI version 3.9.1

Gulp- building project

Use Gulp to build the project:

mkdir Gulp && cd Gulp && npm init -y && npm install gulp --save-dev
#使用npm初始化项目并且安装Gulp模块,能够看到如下的package.json文件中已经包含了Gulp的相关信息。
{
  "name": "Gulp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "^3.9.1"
  }
}

gulpfile.js file use:

gulp also need a file as its master file, this file is called in a gulp in gulpfile.js.

Creating gulpfile.js file, like package.json file in the root directory of the project, after the gulpfile.js need to do is file defined task.

Gulpfile.js write the following in the file:

    var gulp = require('gulp');
    gulp.task('default', function() {
      console.log("Gulp OK!");
    });

After completing the Terminalrun gulpcommand, and then just see something in the task task to be output.

➜  gulp
[00:35:29] Using gulpfile ~/WebStrom-Work/Gulp/gulpfile.js
[00:35:29] Starting 'default'...
Gulp OK!
[00:35:29] Finished 'default' after 141 μs

Gulp- API

gulp.src()

grammar:

gulp.src(globs[, options])

File output (Emits) meet the matching pattern (glob) provided to match the pattern or array (array of globs) a. Vinyl files will return a stream of it can be piped to other plug-ins.

name Types of meaning
globs String 或 Array To be read comprises globs or glob array.
options Object Parameter node-glob transmitted to by the glob-stream.

gulp.dest ()

grammar:

gulp.dest(path[, options])

Pipe can come in, and will write files. And to re-outputs (emits) all data, so you can pipe it into multiple folders. If a folder does not exist, it will automatically create it.

  • Type path: the path (the output directory) String or Function, the file to be written. Can also pass a function that returns the corresponding path function, this function may also be provided by the vinyl file instance.

  • options
    Type: Object, is an optional parameter object, usually we do not need to use

gulp.task()

grammar:

 gulp.task(name[, deps], fn)
  • name
    Type: Name String, task, if you need to run some of your tasks from the command line, then please do not use spaces in the name.

  • deps
    Type: Array, an array that contains a list of tasks, these tasks will be completed in the current task before you run.
    $xslt demo gulp.task('mytask', ['array', 'of', 'task', 'names'], function() { // 做一些事 });
    Note: Your task is running prior to these pre-dependent task is completed? Make sure you rely on a list of tasks in the task using the correct asynchronous execution mode: use a callback, or a promise to return or stream.

  • fn
    Some operations This function is defined tasks to be performed. Generally speaking, it is this form:gulp.src().pipe(someplugin())。

gulp.watch()

grammar:

gulp.watch(glob[, opts], tasks)

gulp.watch () is used to monitor changes in the file, when the file changes, we can use it to perform the appropriate task.

  • globType: String or Array, a glob string, or an array comprising a plurality of strings glob, to specify which files to monitor specific changes.

  • opts Type: Object

Gaze of parameters passed.

  • cb(event)
    Type: Function, every change callback to be executed.

Reference: the Gulp the API-

Gulp- common plug-ins

Compression JS -> gulp-uglify:

Installation gulp-uglify:

 npm install gulp-uglify --save-dev 

Sample code:

var gulp = require('gulp');
var uglify = require('gulp-uglify');

gulp.task('javascript',function () { // javascript: 任务名称
    gulp.src('./src/js/*.js')  // src: 定位到需要压缩的js文件目录下
        .pipe(uglify()) // 执行压缩文件
        .pipe(gulp.dest('./dist/js')); // 输出到指定目录
});

API Reference: GULP-uglify

Compression CSS -> gulp-minify-css:

Installation gulp-minify-css:

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

Sample code:

var gulp = require('gulp');
var minify = require('gulp-minify-css')

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

API Reference: GULP-CSS-Minify

Compress pictures -> gulp-imagemin:

Installation gulp-imagemin:

npm install gulp-imagemin --save-dev

Sample code:

var gulp = require('gulp');
var image = require('gulp-imagemin');

gulp.task('image',function () {
    gulp.src('./src/images/*.*')
        .pipe(imagemin())
        .pipe(gulp.dest('./dist/images'));
});

API Reference: Gulp-Imagemin

Compile Less-> gulp-less:

Installation gulp-less:

npm install gulp-less --save-dev

Sample code:

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

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

API Reference: GULP-less

Auto Refresh -> gulp-livereload:

Installation gulp-livereload:

npm install gulp-livereload --save-dev

Sample code:

在每个gulp.task()方法中的gulp.src()方法后追加   .pipe(livereload());    即可。

We need to meet the Google browser plug-in LiveReloadplug-ins to use, automatic refresh.

API Reference: GULP-livereload

Google Chrome Plugin:LiveReload

Complete gulpfile.jsfile:

var gulp = require('gulp'); // Gulp
var uglify = require('gulp-uglify');  // JavaScript
var minify = require('gulp-minify-css'); // CSS
var imagemin = require('gulp-imagemin'); // Images
var less = require('gulp-less'); // Less
var livereload = require('gulp-livereload') // LiveReload

// 执行所有任务
gulp.task('default', ['javascript','css','less','image']);

gulp.task('javascript',function () { // jsscript: 任务名称
    gulp.src('./src/js/*.js')  // src: 定位到需要压缩的js文件目录下
        .pipe(uglify()) // 执行压缩文件
        .pipe(gulp.dest('./dist/js')); // 输出到指定目录
});



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

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


gulp.task('image',function () {
    gulp.src('./src/images/*.*')
        .pipe(imagemin())
        .pipe(gulp.dest('./dist/images'));
});

Gulp- References

Common web project directory:

Executed in the root directory of the current project treecommand, you can see the entire directory structure of the project, if there is no treecommand in Mac systems can be used brewto install:

➜  Glup tree ../Glup
../Glup

├── build # 项目构建脚本
├── src # 源码目录
│   ├── css # CSS文件
│   ├── fonts # 字体文件
│   ├── images # 图片文件
│   ├── js # js脚本文件
│   ├── less # less文件
│   └── sass # sass文件
├── dist # 编译出来的发布版本目录
│   ├── css 
│   ├── fonts
│   ├── images
│   └── js 
├── docs # 文档
├── test # 测试脚本
├── gulpfile.js # Gulp工具构建项目的主文件
├── node_modules # npm包存放目录
├── package-lock.json #npm5.0以上项目依赖文件
├── package.json # npm包管理配置文件
├── LICENSE # 授权协议
└── README.md # 项目说明文件

Guess you like

Origin www.cnblogs.com/zhangyangdev/p/11445798.html