Home  >  Article  >  Web Front-end  >  Gulp usage quick memory

Gulp usage quick memory

韦小宝
韦小宝Original
2018-03-14 12:41:072012browse

This article talks about the usage of gulp, and how we can quickly memorize the usage of gulp. For those of you who don’t know much about the usage of gulp, we can take a look at this article together!

Writing steps:
1. How to install
2. How to use

1. How to install
First you have to install nodejs on your computer, because the running of gulp is based on the nodejs environment.
After the installation is completed, directly npm install gulp -g. (If you don’t understand this code, please ask Baidu.) After the installation is completed, you can directly call the gulp function in the cmd window.
2. How to use
What is the role of gulp?
We build a project named app, which contains css folder, js folder, image folder and html file. Usually the files in the folder will have spaces and comments. These files are relatively large to transfer and the transfer efficiency is low. So if we want to compress these files, we will use gulp.
How to use gulp?
1. Create a gulpfile.js file directly in the project directory, and then run the corresponding command in the cmd window to execute gulpfile.js.
For example, I want to compile a js file. The app file structure is as follows:

Gulp usage quick memory

Next we start writing the gulpfile file:

var gulp = require('gulp');//引入gulp模块
var uglify = require('gulp-uglify');
//引入gulp-uglify模块,用来压缩js文件。如果要压缩css文件就要引入gulp-minify-css模块。这些模块都要通过npm包管理器来安装。安装之后app文件中会自动出现一个叫node_modules的文件夹。如果你在全局安装了gulp,这里建议你进入到该项目文件夹再安装一次,避免后面gulp更新之后影响文件运行。

//执行压缩任务。创建一个名为script的任务(随意取名),在cmd中输入gulp script会执行该任务,即运行后面的function功能
gulp.task('script',function(){
    gulp.src('js/*.js')//获取文件地址
         .pipe(uglify())//执行编压缩功能。如果是压缩css则把来自于gulp-uglify的uglify()方法转换成gulp- minify-css模块中的minifyCSS功能。
         .pipe(gulp.dest('dist/js'));//输出文件位置,在dist文件夹下的js文件夹内。如果项目中不存在dist的文件,会自动创建。
})

//编译完成,如果我们修改原js文件,要使压缩文件也自动改变怎么办。这个时候我们就要对原js文件进行监听,如果发现有改动则重新编译。代码如下:
//执行监听任务
gulp.task('auto',function(){// 创建一个监听任务。
    //监听文件修改,当文件被修改则执行script人物
    gulp.watch('js/*.js',['script']);//第一个参数表示监听的文件,第一个参数表示重新执行script人物。
})
//所有的任务要在cmd中输入gulp+任务名后才能执行。这样不太方便,可不可以在定义任务,它的作用就是执行执行之后可以执行所有的人物。
//有,如下:
//gulp.task('default')定义默认任务
//在命令行使用gulp启动script任务和auto人物
gulp.task('default',['script','auto']);
//这样我们直接在cmd中输入gulp就会执行script和auto这两个任务。

Summarize the following gulp Function:

  • gulp.task('task name', function(){}) defines a task

  • gulp.src()/ /Find the current file address

  • gulp.desk()//Output file

  • gulp.pipe()//Can be understood as a pipe , add the operation to the execution queue.

3. Compress or compile other files (just compare js)
1. Compile css files
Block name: gulp-minify-css
Compressed fileFunction:minifyCSS

2. Compressed image
Block name: gulp- imagemin
Compress file function: imagemin({progressive})

3. Compile less
Block name: gulp-less
Compilation method: less();

4. Use gulp to build a project

1. Create package.jsonconfiguration file in cmd, It contains your dependency package information.
Install the corresponding module and the module name will be added to package.json.
2. DesignDirectory structure
Divide the files into two categories: the dist/ directory is the compressed code, and the src/ directory is the source code file.

How to make the output of gulp have time and color. gulp-util has the same effect, but its color effect is richer.
Introduce the module gulp-util

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 usage quick memory
It is emphasized here that the gulp operation must enter the project folder, that is, the interface where the node_modules folder is located, in order to perform the gulp operation in the cmd window.
4. How to configure js files
There is a problem with the above writing method. As long as one js file is modified, all js files will be recompiled.
What if we only want to compile the modified files?
Use 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))


})


})

If we have a format error when editing the source code, how to output this error? Use 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)
})
})

The compressed code does not exist Newline characters and whitespace characters make it difficult to debug after an error occurs. Fortunately, we can use sourcemap to help debug

var sourcemaps = require('gulp-sourcemaps')
// ...
var combined = combiner.obj([
gulp.src(paths.srcPath),
sourcemaps.init(),
uglify(),
sourcemaps.write('./'),
gulp.dest(paths.distDir)
])
// ...

At this time, the corresponding .map file will also be generated in dist/js/ for debugging using the Chrome console Code

gulp-autoprefixer – Parses CSS files and adds browser prefixes to CSS rules. These prefixes will be added during compilation

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))//输出文件
})
})

Related recommendations:

What you need to know to get started with gulp

The above is the detailed content of Gulp usage quick memory. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn