Gulp+webpack Configuration

Source: Internet
Author: User


transferred from: Https://www.jianshu.com/p/2549c793bb27Gulp

Gulp is a tool for building the code in the front-end development process, and is the building block of the automation project; She not only optimizes the site resources, but also many repetitive tasks can be done automatically with the right tools during the development process. Using her, we can not only happily write code, but also greatly improve our efficiency.
Gulp is a NODEJS-based automatic task runner that automates the testing, checking, merging, compressing, formatting, automatic browser refresh, and deployment file generation of JAVASCRIPT/COFFEE/SASS/LESS/HTML/IMAGE/CSS and other files. And listen for files that repeat the specified steps after the change. In the implementation, she borrowed from the Unix operating system pipeline (pipe) thought, the previous level of output, directly into the back-level input, making it very simple to operate. Through this article, we will learn how to use Gulp to change the development process to make development faster and more efficient.
Gulp and Grunt are very similar, but the gulp flow operation is faster and easier to build than Grunt's frequent IO operations.

Webpack

Webpack is now the most popular modular management and packaging tool for front-end resources. It can package many loose modules according to dependencies and rules into front-end resources that meet the deployment of the production environment. You can also code-separate modules that are loaded on demand, and then load asynchronously when you actually need them. With loader conversion, any form of resources can be seen as modules, such as CommonJs modules, AMD modules, ES6 modules, CSS, images, JSON, coffeescript, less and so on.

* * Of course individuals still like Webpack's modular Excellent

Don't say much nonsense now start Gulp Tour

Initialize project (the node environment is already considered installed here)

Create a folder name yourself like Gulptext, then enter the following command

$ cd  gulpText$ mkdir images    //建立存放图片文件夹$ mkdir src       //  存放 js 以及css$ mkdir index.html   //主页$ mkdir gulpfile.js       //编写gulp 任务文件$ mkdir mock       //mock数据

Then enter the following command and then go all the way to generate the JSON file.

$npm init

Open the JSON file and see this

1474889102536.png

Global Installation Gulp So we can run gulp for packaging and more

$npm install gulp -g

If you feel that NPM installation is slow, you can switch to CNPM download, the code is as follows

$npm install cnpm -g

Install the gulp package to facilitate our reference gulp

$npm install gulp

Success

1474889517162.png

Writing gulp tasks to introduce gulp
//引入gulpvar gulp  = require(‘gulp‘);
Copy index.html
//copyhtmlgulp.task(‘copy-index‘,function () { gulp.src(‘./index.html‘) .pipe(gulp.dest(‘./build‘));})

Execute command

  $ gulp copy-index

1474890843877.png] (//upload-images.jianshu.io/upload_images/2905209-c00d640651bde279.png?imagemogr2/ auto-orient/strip%7cimageview2/2/w/1240)

1474890828271.png

Copy Images
//copy imagesgulp.task(‘copy-images‘,function () { gulp.src(‘./images**/*‘) .pipe(gulp.dest(‘./build/‘));})

Execute command

  $ gulp copy-iamges
1474891076408.png
1474891039689.pngcss pretreatment

Now we create the file in the SRC directory styles to put our SCSS code, we need to compile the SCSS code to/build/prd/styles/

$ cd src$ mkdir styles$ cd styles$ touch app.scss$ touch common.scss

APP.SCSS Project Code

@CharSet"UTF-8";Import"./common.scss";body{background-color:  $base-color; color:  #000; font-size: 20px; font-weight: 800;} html{width: 100%; height:  100%;} html{width: 100%; height:  100%;} .lsds{width: 100px; Span class= "Hljs-attribute" >height: 100px;}        

COMMON.SCSS Code

$base-color:yellow;

To install a CSS precompiled package

$ npm install gulp-sass   //sass编辑包$ npm install gulp-minify-css‘);  //css压缩包
//引入css预处理模块var  sass= require(‘gulp-sass‘);//引入css压缩模块var minifyCSS = require(‘gulp-minify-css‘);//css预处理var cssFiles=[ ‘./src/styles/app.scss‘];gulp.task(‘scss‘,function () { gulp.src(cssFiles) .pipe(sass().on(‘error‘,sass.logError)) .pipe(minifyCSS()) .pipe(gulp.dest(‘./build/prd/styles/‘))})

Edit Scss

$ gulp scss
Open service

Installing the server package

 $ npm install gulp-webserver
//引入gulp-webserver 模块var server = require(‘gulp-webserver‘);gulp.task(‘server‘,function () { gulp.src(‘./‘) .pipe(server({ host:‘127.0.0.1‘, //ip port:80, //端口 directoryListing:{ enable:true, path:‘./‘ }, livereload:true, }));})
Open Service Command
 $ gulp server

And then you have access to 127.0.0.1.

Add Watch
Detects file changes and performs the corresponding task Gulp.task (' Watch ',function () {Gulp.watch ('./index.html ', [' Copy-index ']); Gulp.watch ('./images/**/* ', [' copy-images ']); Gulp.watch ('./ src/styles/*. {scss,css} ', [' scss ',' min ']); //Remove min //Gulp.watch ('./src/scripts/*.js ', [' Packjs ', ' min '])//This line is first used after configuring JS compilation}) The first parameter represents the listening file the second parameter is the task to perform//configure the default task, execute the task queue Gulp.task (' default ', [' Watch ',' server '), function () { console.log (' task queue execution completed ');})          
Configure Webpack

Mounting module

$ npm install vinyl-named$ npm install gulp-webpack$ npm install gulp-uglify
Introduce JS Modular tool gulp-webpack, get JS file module VINYL-NAMED,JS Compression modulevar named =Require' vinyl-named ');var webpack =Require' Gulp-webpack ');var uglify =Require' Gulp-uglify ');var jsfiles = ['./src/scripts/app.js '];gulp.task (' Packjs ',function (output:{filename: ' [Name].js '}, module:{loaders:[{test: /\.js$/, loader: ' imports?define= >false '}]}). Pipe (Uglify (). On ( ' error ', function (err) {console.log ( ' \x07 ', err.linernumber,err.message); return this.end ();})) . Pipe (Gulp.dest (      
Mock data

Add the entire service code in the Service module to

Gulp.task (' Server ',function () {GULP.SRC ('./'). Pipe (Server ({Host' 127.0.0.1 ',Port80,directorylisting:{EnableTruePath‘./‘ },Livereload:TrueHot updateMock data middleware:functionReq,res,next) {var urlobj =url.parse (Req.url,true);Req.url is the entire URL urlobj is the requested information setSwitch (urlobj.pathname) {case  '/api/orders ': Res.setheader (  ' Comtent-type ',  ' Application/json '); ////Return body format fs.readfile ( './mock/list.json ', function (err,data) { //Read file if (err) {res.send ( ' Read File error ‘); //Error returned} res.end (data); //return JSON data}); return; case  '/api/users ': return; case  '/api/cart ': return;} next ();})))  
Version control

Upgrade Plugin

 $ npm install gulp-rev $ npm install gulp-rev-collector $ npm install gulp-sequence
Introducing the FS URL modulevar fs =Require' FS ');var url =Require' URL ');Introduction of Rev Revcollector module provides control of version number functionvar rev =Require' Gulp-rev ');var revcollector=Require' Gulp-rev-collector ');Introducing the Gulp-sequence modulevar sequence =Require' Gulp-sequence ');Version number controlvar cssdistfile = ['./build/prd/styles/app.css '];var jsdistfile = ['./build/prd/scripts/app.js '];gulp.task (' Ver ',function) {GULP.SRC (cssdistfile)The file path to execute. PIPE (rev ())Build version number. PIPE (Gulp.dest ('./build/prd/styles/') copies a copy of APP.CSS. Pipe (Rev.manifest ())* Generate the following JSON file in this format {"App.js": "App-8232057589.js"}. Pipe (Gulp.dest ('./build/ver/styles/')) //Copy this file to the specified place Gulp.src (jsdistfile). Pipe (rev ()). Pipe (Gulp.dest ('./build/prd/scripts/')). PIPE ( Rev.manifest ()). Pipe (Gulp.dest ('./build/ver/scripts/')}); Gulp.task (' HTML ',function () {GULP.SRC (['./build/ver/**/* ','./build/*.* ']). Pipe (Revcollector ()). Pipe (Gulp.dest ('./build ');}); Gulp.task (' min ', sequence (' Copy-index ',' ver ',' html ')); //sequence serial execution parallel use []              

Gulp+webpack Configuration

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.