Gulp CSS, JS, img compression and CSS images BASE64__JS

Source: Internet
Author: User
Tags base64 md5

Before studying, we should talk about the steps of using gulp and give the readers a preliminary understanding. First of course is to install Nodejs, through the Nodejs NPM Global installation and Project Installation Gulp, and then install the required Gulp Plug-ins in the project, Then create a new Gulp profile gulpfile.js and write the configuration information (define Gulp Tasks), and then run the Gulp task from the command prompt.

Install Nodejs-> Global Installation Gulp-> Project installation Gulp and Gulp plug-in-> configuration gulpfile.js-> Run task 1, install Nodejs

1.1, Description: Gulp is based on Nodejs, of course, the need to install Nodejs;

1.2, Installation: Open Nodejs official website, click the huge green Download button, it will be based on system information to select the corresponding version (. msi file). Then install it like a QQ installation (installation path is optional).

2, use the command line (if you are familiar with the command line, you can skip to step 3rd)

2.1, Description: What is the command line. The command line at OS X is the terminal (Terminal), at Windows is the command prompt (commands Prompt);

2.2, note: After the operation is under the Windows system;

2.3, a brief introduction gulp in the use of common commands, open a command prompt to execute the following command (open: Window + R input cmd carriage return):

node-v View the Nodejs version of the installation with the version number indicating that Nodejs was just installed correctly. PS: Failed to appear version number, please try to log off the computer retry;

npm-v See NPM's version number, and NPM is the Nodejs Package Manager that was installed together while installing Nodejs, so what's the use of it? Explain later;

CD location to directory, usage: cd + path;

dir lists file lists;

The CLS empties the contents of the Command Prompt window.


3, NPM introduction

3.1. Description: NPM (Node Package Manager) Nodejs Package Manager for node plug-in management (including installation, uninstall, management dependencies, etc.);

3.2. Use NPM to install Plugins: command prompt to perform npm install <name> [g] [--save-dev];

3.2.1,<name>: Node plug-in name. Example:npm install gulp-less--save-dev

3.2.2,G: Global installation. will be installed on the C:\USERS\ADMINISTRATOR\APPDATA\ROAMING\NPM and written to the system environment variable; non-global install: will be installed in the current location directory; global installation can call it anywhere from the command line, Local installation will be installed in the location directory of the Node_modules folder, through the Require () call;

3.2.3,--save: Will save configuration information to Package.json (Package.json is nodejs project configuration file);

3.2.4,-dev: Save to the Devdependencies node of the Package.json, do not specify that-dev will be saved to the dependencies node; generally stored in dependencies like these express/ Ejs/body-parser and so on.

3.2.5, why to save to Package.json. Because the node plug-in package is relatively large, it does not add version management, writes configuration information to Package.json and adds it to version management, and other developers download it (the command prompt executes npm install, All required packages are downloaded according to the Package.json.

NPM install--production only download packages for dependencies nodes).

3.3. Use NPM Uninstall plugin:npm uninstall <name> [g] [--save-dev] PS: Do not delete the local plug-in package directly

3.3.1, remove all plugins:npm uninstall gulp-less gulp-uglify gulp-concat...??? Too much trouble

3.3.2, with the help of Rimraf:npm Install rimraf-g usage:rimraf node_modules

3.4, use NPM Update plugin:npm update <name> [g] [--save-dev]

3.4.1, update all plugins:npm Update [--save-dev]

3.5. See NPM Help:npm helps

3.6, the current directory has installed Plug-ins:NPM list

PS:NPM Install plug-in process: Download the corresponding plug-in package from http://registry.npmjs.org (the Web server is located abroad, so often download slowly or abnormal), the solution to look down ↓↓↓↓↓↓.

4. CNPM of optional equipment

4.1, Description: Because NPM installation plug-ins are downloaded from a foreign server, affected by the network, may appear abnormal, if NPM's server in China, so we would like to share the Taobao team did this thing. From the official website:"This is a full npmjs.org mirror, you can use this instead of the official version (read only), Sync frequency is currently 10 minutes to ensure that as far as possible with the official service synchronization." ";

4.2, official website: http://npm.taobao.org;

4.3. Install: Command prompt to perform npm install cnpm-g--registry=https://registry.npm.taobao.orgNote: It is best to view its version number after installation cnpm-v or turn off the command prompt and turn it back on, and there may be an error in the direct use of the installation.

Note: CNPM is exactly the same as NPM usage, except that NPM is changed to CNPM when the command is executed (the following actions will replace NPM with CNPM).

5. Global Installation Gulp

5.1, Description: Global Installation Gulp purpose is to carry out the gulp task through her;

5.2, Installation: command Prompt to execute cnpm install gulp-g;

5.3, to see whether the correct installation: command prompt to perform gulp-v, the version number is installed correctly.

6. New Package.json file

6.1, Description: Package.json is based on the NODEJS project is an essential configuration file, it is stored in the project root directory of ordinary JSON file;

6.2, it is such a JSON file (Note: The JSON file is not write comments, copy the following to delete the comments):

{
  "name": "20180101", "
  Version": "1.0.0",
  "description": "",
  "main": "Gulpfile.js",
  "scripts": {
    "test": "Echo \" Error:no test specified\ "&& exit 1"
  },
  "author": "",
  "license": "ISC",
  "Devdependencies": {"
    Gulp": "^3.9.1",
    "gulp-base64": "^0.1.2",
    "gulp-htmlmin": "^4.0.0", "
    gulp-imagemin": "^4.1.0", "
    gulp-livereload": "^3.8.1",
    "gulp-minify-css": "^1.2.4",
    " Gulp-processhtml ":" ^1.2.0 ","
    Gulp-rev ":" ^8.1.1 ",
    " Gulp-rev-collector ":" ^1.2.4 ",
    " gulp-uglify ":" ^3.0.0 "
  }
}

6.3, of course, we can manually create this profile, but as a young aspiring, we should use a more efficient approach: command prompt to execute CNPM init

6.4, view the Package.json Help document, command prompt to perform cnpm assistance Package.json

Special Note: Package.json is a normal JSON file, so you cannot add any comments.

7. Install Gulp plugin Locally

7.1, Installation: Location directory command after the prompt execution cnpm Gulp install--save-dev;

7.2. This example takes gulp-less as an example (compiling the less file), and the command prompt executes the cnpm install gulp-less--save-dev;

7.3, will be installed in the Node_modules gulp-less directory, the directory has a gulp-less use of help documents readme.md;

PS: Careful you may find that we have a global installation of Gulp, the project also installed Gulp, the global installation Gulp is to perform gulp tasks, local installation Gulp is to invoke the functionality of the Gulp Plug-ins.

8, new Gulpfile.js file (important)

8.1, Description: Gulpfile.js is the Gulp project configuration file, is located in the project root directory of ordinary JS file (in fact, the gulpfile.js into other folders can also be).

8.2, it is probably such a JS file:

var gulp = require (' gulp ') Cssmin = require (' gulp-minify-css ')//css compression uglify = require (' gulp-uglify ')                JS compression imagemin = require (' gulp-imagemin ')//image compression base64 = require (' gulp-base64 ') -Turn small picture into base64 string htmlmin = require (' gulp-htmlmin ')//html compression//compress CSS file and base64 and filename plus MD5               Suffix gulp.task (' testcssmin ', function () {gulp.src (' css/*.css '). Pipe (base64 ())//. Pipe (rev ())
        File name plus MD5 suffix. Pipe (cssmin ())//. Pipe (Rev.manifest ())//rev-mainfest.json files, which contain information about compressed files
. Pipe (Gulp.dest (' dist/css '));

}); Compressed JS file Gulp.task (' script ', function () {//1. Find File Gulp.src (' js/*.js ')//2. compress file. Pipe (Uglify ({ Mangle:false}))//3. Save the compressed file. Pipe (Gulp.dest (' Dist/js ')})//compress img file gulp.task (' Testimagemin ', function () {GULP.SRC (' images/* . {Png,jpg,gif,ico} '). Pipe (Imagemin ({optimizationlevel:5,Type: Number default: 3 Value range: 0-7 (Optimization level) progressive:true,//Type: Boolean default: False lossless compression jpg picture interlaced:t
        Rue,//Type: Boolean default: False interlaced GIF for rendering multipass:true//type: Boolean default: False multiple optimizations to optimize SVG until full optimization})
. Pipe (Gulp.dest (' dist/images '));
}); Compressed HTML file gulp.task (' Testhtmlmin ', function () {var options = {removecomments:true,//clears HTML annotations coll apsewhitespace:true,//Compressed HTML collapsebooleanattributes:true,//omits the value of the Boolean property <input checked= "true"/> ==> < Input/> removeemptyattributes:true,//Delete all spaces for property values <input id= ""/> ==> <input/> ripttypeattributes:true,//Delete <script> type= "text/javascript" removestylelinktypeattributes:true,//Delete <st
    Yle> and <link> type= "text/css" minifyjs:true,//compressed page JS minifycss:true//compressed page CSS};
GULP.SRC (' *.html '). Pipe (Htmlmin (options)). Pipe (Gulp.dest (' dist/'));


}); Listening for file changes/* Gulp.task (' WAtch ', function () {Livereload.listen ();
    Gulp.watch ([' Css/*.css '], [' testcssmin ']);
    Gulp.watch ([' Js/*.js '], [' script ']); Gulp.watch ([' images/*.{
    Png,jpg,gif,ico} '], [' testimagemin ']);
Gulp.watch (['/*.html '], [' testhtmlmin ']); }); * * Combined with my method to monitor and perform the task * * gulp.task (' default ', [' testcssmin ', ' script ', ' testimagemin ', ' Testhtmlmin ',//' watch ']);
Refer to the above gulpfile.js we put the static resources into CSS, JS, images, and then copy the file to the directory dist.
Then we have to do is to compress dist files to CSS, JS, images and real-time monitoring changes.
9. Operation Gulp

9.1, Description: Command prompt to perform gulp task name;

9.2, compile Less: command prompt executes Gulp testless;

9.3, when executing gulp default will invoke all tasks in the default task [' Testcssmin ', ' script ', ' testimagemin ']. 10. Summary Then we can make changes in real time and the browser can go to real-time display code





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.