Learn to write front-end configuration of the site (b) glup

Front-end gulpto automate the development process.

gulp will be very convenient for front-end management.

Installation gulp:

npm install gulp -g #将gulp安装至全局

Because the need to use local requiremode gulp. Therefore also need to install a locally:

npm install gulp --save-dev  #将gulp安装至本地,并保存至package.json

Above --save-devis added to the package to be installed package.jsonunder the devDependenciesdependence. After passing npm installto automatically install. devDependenciesThis package is used to record the use of the development environment, if you want to record package uses production environment, use when installing the package npm install xx --savewill be recorded package.jsonin the dependenciesmiddle, dependenciesis designed to record dependencies in the production environment !

Create a gulp tasks:

To use gulpour development efforts to streamline. First you need to create a project in the root directory of gulpfile.jsthe file. Then gulpfile.jsfill the following code:

var gulp = require("gulp")

gulp.task("greet",function () {
    console.log('hello world');
});

  

By requirestatement references have installed third-party dependencies. This requirecan only be a reference to the current project, it can not be referenced under global. requireThe syntax is node.jsunique and can only node.jsuse environment.

gulp.taskIt is used to create a task. gulp.taskThe first parameter is the name of the command, the second argument is a function, it is time to execute the command will do something, are written in the inside.

After writing the above code, if you want to later execute greetcommand, then only you need to enter the path to the project is located, and then use the terminal gulp greetto perform.

4. Create a task processing css file:

gulpOnly provides a framework for us. If we want to achieve some of the more complex functions, such as csscompression, then we also need to install some gulp-cssnanoplugins. gulpThe associated plug-in installation also through the npmcommand to install, the installation package is exactly the same with the other (gulp plug-in itself is an ordinary package).
To cssprocess the file, you need to do is compressed, then the compressed files are then placed in the specified directory (and do not coincide with the original css files)! Here we use gulp-cssnanoto handle this work:

npm install gulp-cssnano --save-dev

 

Then gulpfile.jswrite the following code:

var gulp = require("gulp")
var cssnano = require("gulp-cssnano")
View Code

 

// define a css file processing task changes 
gulp.task ( "css", function () { 
    gulp.src ( "./css/*.css" ) 
    .pipe (cssnano ()) 
    .pipe (gulp.dest ( "./css/dist/" )) 
});

 

More detailed explanation of the code:

gulp.task: Create a csstask processing.

gulp.src: Find the current cssall to the directory .cssat the end of the cssfile.

pipe: Pipeline method. The method returns a result to the other processor. Such as the above cssnano.

gulp.dest: The file has been dealt with, and put under the specified directory. Do not put the same directory as the original file, in order to avoid conflict, not easy to manage.

5. Modify File Name:

Like the above tasks, compressed complete cssthe file, it is best for him to add a .min.csssuffix, so one can know this is the result of the compressed file. This time we need to use gulp-renameto modify. First, of course, also need to be installed npm install gulp-rename --save-dev. Sample code is as follows:

var gulp = require("gulp")
var cssnano = require("gulp-cssnano")
var rename = require("gulp-rename")
gulp.task("css",function () {
    gulp.src("./css/*.css")
    .pipe(cssnano())
    .pipe(rename({"suffix":".min"}))
    .pipe(gulp.dest("./css/dist/"))
});

 

 

In the above code, increasing the line .pipe(rename({"suffix":".min"})), we are using this renamemethod, and pass an object parameter specifies the rule changes name to add a .minsuffix. That gulp-renamethere are other ways to specify a file name, for example, you can add a prefix such as in front of the file name. More tutorials can look at this: https://www.npmjs.com/package/gulp-rename.

6. Create a task processing js file:

Processing jsfiles, we need to gulp-uglifyplug. Installation command as follows:

npm install gulp-uglify --save-dev

 

After installation, we will be able to jsbe processed files. Sample code is as follows:

var gulp = require("gulp")
var rename = require("gulp-rename")
var uglify = require('gulp-uglify');
gulp.task('script',function(){
    gulp.src(path.js + '*.js')
    .pipe(uglify())
    .pipe(rename({suffix:'.min'}))
    .pipe(gulp.dest('js/'));
});

 

 

Here is the addition of a .pipe(uglify())processing for jsfile compression and vilify (modify variable names) and other treatment. More about gulp-uglifytutorials. Take a https://github.com/mishoo/UglifyJS2#minify-optionslook: .

7. Merge multiple files:

In web development, in order to speed up page rendering speed, and sometimes we will compress multiple files into a single file, thereby reducing the number of requests. To splicing file, we need to use gulp-concatplug-ins. Installation command as follows:

npm install gulp-concat --save-dev

For example, we now have a nav.jsfile used to control the navigation bar. There is a index.jsfile used to control the entire contents of the home. Then we can use the following code to these two files into one file:

var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
gulp.task('vendorjs',function(){
    gulp.src([
        './js/nav.js',
        './js/index.js'
    ])
    .pipe(concat('index.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist/js/'));
});

 

 

8. Compress Pictures:

Pictures are a major limiting site load speed. The larger the picture, from the website the longer it takes to download. So for some pictures, we can take a lossless compression that does not change the basic picture quality of compressed above. In the gulpmiddle we can gulp-imageminto help us achieve. Installation command as follows:

npm install gulp-imagemin --save-dev

 

Image compression is a relatively large amount of work has been compressed for some pictures, we have no need to repeat compressed. At this time we can use gulp-cacheto cache those compressed images. Installation command as follows:

npm install gulp-cache --save-dev

 

Plug-in combination of two codes are as follows:

var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
gulp.task('image',function(){
    gulp.src("./images/*.*")
    .pipe(cache(imagemin()))
    .pipe(gulp.dest('dist/images/'));
});

 

 

9. modification detection code, automated tasks:

All of the above tasks, we all need to perform manually in the terminal. So inconvenient that we develop. The best way I modified the code, gulpwill automatically perform the appropriate task. This work we can use gulpthe built-in watchmethod to help us complete:

var GULP = the require ( "GULP" )
 var cssnano = the require ( "GULP-cssnano" )
 var the rename = the require ( "GULP-the rename" ) 

// define a css file processing task changes 
gulp.task ( "css", function () { 
    gulp.src ( "./css/*.css" ) 
    .pipe (cssnano ()) 
    .pipe (the rename ({ "suffix":. "min" })) 
    .pipe (gulp.dest ( . " / CSS / dist / " )) 
    .pipe (connect.reload ()) 
}); 

// define a listener's task 
gulp.task (" watch ",function () {
     // listen to all css files, and then perform this task css 
    gulp.watch ( "./ css / *. css", [ 'css'])
});

 

 

After as long as the terminal execute gulp watchcommands automatically monitor all cssfiles, and then automatically performs cssthe task, to complete the work.

10. After changing the file, auto-refresh browser:

We realize the above change some of cssthe file, it can automatically perform processing csstasks. But we still need to manually refresh your browser to see the results after modification. Is there any way after modifying the code, it automatically refresh your browser. The answer is to use browser-sync. browser-syncThe installation command is as follows:

npm install browser-sync --save-dev

 

browser-syncSample code is as follows:

var GULP = the require ( "GULP" )
 var cssnano = the require ( "GULP-cssnano" )
 var the rename = the require ( "GULP-the rename" )
 var BS = the require ( "Browser-Sync" ) .create () 

gulp.task ( "BS", function () { 
    bs.init ({
         'Server' : {
             'the baseDir': './' 
        } 
    }); 
}); 

// define a css file processing task changes 
gulp.task ( "css" , function () { 
    gulp.src ( "./css/*.css" ) 
    .pipe (cssnano ()) 
    .pipe (the rename ({ "suffix":".min"}))suffix":".min"
    .pipe(gulp.dest( "./css/dist/" )) 
    .pipe (bs.stream ()) 
}); 

// define a listener task 
gulp.task ( "Watch", function () { 
    GULP. Watch ( "./css/*.css",['css' ]) 
}); 

// perform gulp server open server 
gulp.task (" server ", [ ' bs',' watch '])

 

 

Above we have created a bstask, the task will open a 3000port, after we visit htmlwhen the page, you need http://127.0.0.1:3000the way to visit. Then next we define a servertask. This task will be to perform bsand watchtasks, as long as the modified cssfile, it will perform cssthe task, then it will automatically refresh the browser.
browser-syncPlease refer to more tutorials: http://www.browsersync.cn/docs/gulp/.

Guess you like

Origin www.cnblogs.com/ohahastudy/p/10984280.html