Comparison of Gulp and Webpack

Source: Internet
Author: User

In the current front-end development, front-end separation, modular development, version control, file merging and compression, mock data and so on some of the original back-end ideas began to penetrate into the "big front" development. The front-end development process is becoming more and more cumbersome, and today more and more websites have evolved from Web page mode to Webapp mode. They run in modern high-level browsers, using newer technologies such as HTML5, CSS3, ES6 and more to develop rich features that are more than just a basic requirement for browsing, and that WebApp is usually a single-page application (SPA), where each view is loaded asynchronously. This results in more and more JavaScript code being loaded during page initialization and usage, which poses a huge challenge to the front-end development process and resource organization.

The main difference between front-end development and other development work is that the front-end is based on multi-lingual, multi-layered coding and organization work, followed by the front-end product delivery is browser-based, these resources are incrementally loaded to the browser side, how to organize these fragmented code and resources in the development environment, and ensuring that they load and update quickly and gracefully on the browser side requires a modular system that is the ideal modular system that the front-end engineers have been exploring for years.

This paper needs some basic concepts of Gulp and Webpack, and has a certain understanding of the use of Gulp and Webpack.

At the same time also need to have a certain understanding of NPM or CNPM, the COMONJS, AMD specifications have a certain understanding.

Gulp

Gulp is to standardize the front-end development process, to achieve the front-end separation, modular development, version control, file merging and compression, mock data and other functions of a frontend automation building tools. Said the image point, "Gulp is like a product of the assembly line, the entire product from scratch, are to be controlled by the pipeline, in the assembly line we can manage the product." ”

In addition, Gulp is built through a task for the entire development process.

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.

Comparison of Gulp and Webpack feature implementations

A brief introduction to Gulp and webpack conceptual problems and the big environment, next into the topic of this article, compare the pros and cons of Gulp and Webpack. Compare gulp and Webpack from basic concepts, start-up local server, sass/less precompilation, modular development, file merge and compression, mock data, version control, component control eight.

Basic concepts

First of all, conceptually, we can clearly see that the focus of gulp and Webpack is different.

Gulp focuses on the control management of the entire process of front-end development (like pipelining), and we can configure the Gulp by not configuring the task (via the Gulp.task () method in Gulp, such as starting server, Sass/less precompilation, File merge compression, etc.) to allow gulp to implement different functions to build the entire front-end development process.

Webpack Some people also called the module Packer , it can also be seen that webpack more focused on module packaging, of course, we can develop all the resources (Pictures, JS files, CSS files, etc.) can be seen as modules, The initial webpack itself was designed to package the front-end JS code, and was later extended to other resources for packaging. Webpack is the processing of resources through the loader (loader) and plugins (plug-ins).

In addition, we know that Gulp is controlling the entire process, so each task configured in its configuration file (Gulpfile.js) can be managed by all resources under that task configuration path in the project.

For example, a task that precompiled a sass file can pre-compile all the Sass files under its configuration path:

Gulp.task (' sass ', function () {gulp.src (' src/styles/*.scss '). Pipe (Sass (). On (' Error ', sass.logerror)). PIPE ( Gulp.dest ('./build/prd/styles/'));//post-compilation Output path});

The above task can ‘src/styles/*.scss‘ preprocess all the files in the directory at the .scss end of the file.

Webpack does not manage resources in this way, it is static analysis based on the dependencies of the modules, and then generates the corresponding static resources (such as) according to the specified rules.

In layman's words, Webpack is entry a portal file (JS file) that needs to be configured through its configuration file (Webpack.config.js), such as

Entry: {app:__dirname + "/src/scripts/app.js",}

Then webpack into the app.js file for parsing, app.js such as:

Introduce scss file Import '. /style/app.scss ';//introduce a dependent module Vargreeter =require ('./greeter.js ');d Ocument.getelementbyid (' root '). AppendChild ( Greeter ());

During parsing, a file is found and then processed according to the app.scss webpack.config.js properties in the configuration file module.loaders to find the processing .scss file loader, and app.scss if there are other dependent files found in the file, continue to process app.scss the file's dependent files , until processing completed the "link" on the dependency file, and then encountered a Greeter.js module, so as before continue to find the corresponding loader to deal with ...

Therefore, the processing of the resource file in Webpack is formed by the dependency generated by the import file, and will not be configured as Gulp, and all the required files under that path will be affected.

Modular development

The so-called front-end modular development, my understanding is that at the time of development, the non-access resources file according to his specific use of classification management, when using the Commonjs, AMD, CMD and other specifications to introduce these resource files into the current file. Then, when testing or last-go-live, these resource files are compressed and merged in accordance with certain requirements, plus version control processing.

Perhaps such an understanding or argument is debatable, but the individual still feels that modularity is the management of content, for the understanding of coupling.

First, start with Gulp and see how the idea of modularization can be exploited in the project. The following is a directory structure for a gulp project:

Gulp |--build: Project Output Path | |--prd:css, JS file output path | |--scripts:js file Output Path | |--styles:css: Version number related file | |--ver. HTML: Compiled index.html |--images: Picture folder |--mock:mock Data folder |--NODE_MODULES:NPM Package Management folder |--SRC: Working Directory | |--scripts | |--libs: Section Three-party dependent library (jquery, etc.) | |--tpls: Template file | |--utils: Tool class Folder | |--views: Page Custom js file | |--app.js:index.html file Entry JS | |--styles: File and Scri The PTS folder is basically the same (in this case I'm referencing a third-party framework, the directory is deeper, not showing) |--gulpfile.js:gulp configuration file |--index.html: Home HTML file |--PACKAGE.JSON:NPM package management profile

In the actual development process, work in the SRC directory, HTML, JS and CSS and other files through the Gulp task configuration, perform the merge and compression output to the build directory (the implementation of the merge compression is described in detail below). In a little more detail:

    1. Create a home page HTML file
    2. Create the corresponding App.js portal file and the App.scss portal file. These two files are only introduced by the COMMONJS specification to the custom JS (or scss) file in their views file , the specific logic does not write this file.
    3. In the views directory to write the JS (or CSS) file logic code, where if multiple files require public logic or tool methods, you can pull out to create a corresponding public method under the Util folder, Then use the COMMONJS specification in the JS (or CSS) file that is needed in the views. The third-party library or framework under the Libs directory is also the idea to refer to.
    4. The Tpls file under the scripts directory is used to place the HTML template in the same way as the reference libs.

The

Outlines the modular ideas I understand, but it is important to point out that Gulp's modular work with JS files is implemented through Webpack, specifically by installing Gulp-webpack modules and related Loader module for JS Modular management. The steps are as follows:

    1. Install a gulp-webpack , vinyl-named , Imports-loader in the project via NPM and String-loader modules (described later in the compression merge module)

       $ npm Install gulp-webpack vinyl-named-d 

      & nbsp;

    2. The
    3. Then introduces the Gulp-webpack module through the COMMONJS specification in the Gulp configuration file Gulpfile.js and makes a simple configuration

      //1. Introduction Gulp-webpack and Vinyl-named module Varwebpack=require (' Gulp-webpack '); Varwebpack=require (' vinyl-named ');//2.js Modular Configuration Varjsfiles = ['./src/scripts/*.js ',]; Gulp.task (' Packjs ', function () {GULP.SRC (jsfiles). Pipe (Uglify (). On (' Error ', function (err) {console.log (' \x07 ', Err.linenumber,err.message); Returnthis.end (); }))//webpack to JS Modular section start. Pipe (Webpack ({output:{filename: ' [name].js '},module:{loaders:[{test:/\.js$/, Loader: '  Imports?define=>false '}, {test:/\.string$/, loader: ' String '}]}));//webpack to JS modular section end. PIPE (concat (' all.js '))
      . Pipe (Gulp.dest ('./build/prd/scripts/')); 

CSS file We also use the same as JS file modular thinking, the use of SASS for modular development, as for the Scss file merge compression configuration, the following will be described in detail.

Next should introduce the webpack of the modular implementation, in fact, there is nothing to say, the file directory and gulp the basic same, but the implementation process to use the plug-in or said modules, different configuration. It is also important to note that Webpack's modular packaging of resource files is handled by the way JS files are handled, such as in the previous section, you may find that I app.js have such a line of code in the portal file

Import '.. /style/app.scss ';

You might have wondered why you introduced the Scss file in the JS file.

This is because Webpack is file-managed through dependencies, so it is necessary to have a dependency on the portal file for the modular management of the style file, app.js so we have introduced the entry file for the style file app.scss app.js (other resources want to be managed, as well as The app.js portal file establishes dependencies).

However, it is obvious that the style files app.js are all merged into the JS file through the portal file, which is obviously not the result we want, so we need to split the style file from the JS file.

    1. Install a extract-text-webpack-plugin module in the project via NPM

       $ npm Install extract-text-webpack-plugin-d 

       

    2. And then make a simple configuration in Webpack configuration file webpack.config.js

      // 1. Introduce the Extract-text-webpack-plugin module Varet =require (' Extract-text-webpack-plugin '); module.exports = {//source-map Debug Devtool: ' Eval-source-map ',//webpack Portal file Configuration entry: {app:__dirname + "/src/scripts/app.js",},//webpack Export file configuration output: { Path: __dirname + "/prd/scripts/",//output file path configuration filename: "bundle.js"//output file name configuration},module:{loaders:[{test:/\.scss$/, Loade R:et.extract (' style ', ' css!sass ')//extracted from JS scss file}]}, plugins: [Newet ('./styles/bundle.css '),//from JS to extract the Scss file output directory settings], Local server configuration devserver: {contentbase: __dirname + '/prd/',//directory where the local server loaded the page is located port:8089,//Local Service port configuration colors:true,// The output in terminal is color historyapifallback:true,//do not jump inline:true//real-time Refresh}} 

Some of the configuration information above is not complete, as described in the following subsections. This allows us to implement the purpose of stripping CSS files from the JS file. Webpack not only can the CSS file can be modularized management, but also to the image of the module management, interested can try it yourself.

File merging and compression

In the above modularity, we mentioned that the modularity is actually a large part of the file merging and compression operations, so we'll look at how Gulp and Webpack are merging and compressing files.

First to look at the big background, because the front-end is more and more large, page file dependencies are more and more, so the reasonable merger and compression of these files will be determined. According to the previous understanding, Webpack should be better than gulp file merging and compression, after all, people are called module Packer .

Conclusion is correct, gulp can be the CSS file and JS file compression processing, and Webpack can be implemented on the CSS files, JS files, HTML files, such as the merging compression and image compression, you can also compile the JS file (such as Es6–>es5,react JSX) and so on, these are achieved through the Webpack loader , of course, these can also be added to Gulp, after all Gulp as a module, Webpack through the introduction of.

Gulp Merging compressed Files CSS compression

To achieve gulp to the CSS file compression only need to install a gulp-minify-css module.

    1. Install a gulp-minify-css module in the project via NPM

      $ NPM Install gulp-minify-css-d

    2. The Gulp-minify-css module is then introduced through the COMMONJS specification in the Gulp configuration file Gulpfile.js and is simply configured

      1. Introduce the GULP-MINIFY-CSS module varminifycss =require (' gulp-minify-css ');//2.css preprocessing varcssfiles = ['./src/styles/usage/page /index.scss ']gulp.task (' sass ', function () {GULP.SRC (cssfiles). Pipe (Sass (). On (' Error ', sass.logerror)). PIPE ( MINIFYCSS ())//performs compression processing on one line. Pipe (Gulp.dest ('./build/prd/styles/'));});

Such a simple CSS compression is implemented.

JS Merge compression

To implement gulp to the JS file merge compression needs to install a gulp-uglify and gulp-concat two modules, the former is for the compression module, the latter is a combined module.

    1. Installing the gulp-uglify and gulp-concat modules through NPM in your project

      $ NPM Install gulp-uglify gulp-concat-d

    2. The gulp-uglify and gulp-concat modules are then introduced in the Gulp configuration file Gulpfile.js via the COMMONJS specification and are simply configured

      1. Introduction of **gulp-uglify** and **gulp-concat** modules varuglify =require (' gulp-uglify '); Varconcat =require (' Gulp-concat ');//js Merge compression varjsfiles = ['./src/scripts/*.js ',]; Gulp.task (' Packjs ', function () {GULP.SRC (jsfiles)//js file compression. Pipe (Uglify (). On (' Error ', function (err) {console.log (' \ \ X07 ', err.linenumber,err.message); Returnthis.end (); }). Pipe (Webpack ({output:{filename: ' [name].js '},module:{loaders:[{test:/\.js$/, loader: ' imports?define=> False '}, {test:/\.string$/, loader: ' String '}]});//js file merge. Pipe (concat (' all.js ')). Pipe (Gulp.dest ('./build/prd/ Scripts/');});

JS file merge compression has also been completed. Let's take a look at the merge compression of Webpack.

Webpack combined compression compression JS and CSS

For JS and CSS file compression, Webpack has embedded uglifyjs to complete the JS and CSS compression confusion, no need to reference additional plugins. We only need to do the following configuration in the plugins attribute in the Webpack configuration file:

Plugins: [Newwebpack.optimize.UglifyJsPlugin ({///Zip code compress: {warnings:false}, except: [' $super ', ' $ ', ' exports ', ' Require ']//exclude keywords}]

It is important to note that when compressing, you need to exclude some keywords, can not be confused, such as $ or require, if the confusion will affect the normal operation of the code.

Compression of HTML

To compress the HTML, you also need to configure the Webpack configuration file, and you need to download two plugins htmlwebpackplugin and html-minifier plugins:

1. Installing the htmlwebpackplugin and html-minifier modules via NPM in the project

$ npm Install htmlwebpackplugin-d$ npm Install html-minifier-d

2. Then configure the Webpack configuration file webpack.config.js as follows:

Plugins: [Newhtmlwebpackplugin ({//] generate final HTML favicon according to template insert Css/js: './src/img/favicon.ico ',//favicon path filename: '/ View/index.html ',//generated HTML store path Template: './src/view/index.html ',//html template path inject:true,//allow plugin to modify what content, including head and body hash:true,//generate hash values for static resources minify:{//Compress HTML files removecomments:true,//Remove comments in HTML collapsewhitespace:true//remove whitespace and newline characters}} ) ]

The Htmlwebpackplugin plugin called the Html-minifier plugin when generating HTML to complete the compression of HTML, where we use two configurations to remove comments from HTML and to compress whitespace characters.

Sass/less Pre-compilation

Let's look at Sass/less pre-compilation, in fact, sass/less the pre-compilation, the difference is not very big. The Gulp is gulp-sass preprocessed by the gulp-less module, while the Webpack is scss-loader preprocessed through, the less-loader loader (loader). Let's take a look at both of these implementations.

Gulp Pre-compiled sass/less

Take sass as an example:

    1. Install a gulp-sass module in the project via NPM

      $ NPM Install gulp-sass-d

    2. The Gulp-sass module is then introduced through the COMMONJS specification in the Gulp configuration file Gulpfile.js and is simply configured

      1. Introduction of the Gulp-sass module Varsass=require (' Gulp-sass ');//2.css preprocessing varcssfiles = ['./src/styles/usage/page/**/* '//./src/ All files under the Styles/usage/page directory];gulp.task (' Sass ', function () {GULP.SRC (cssfiles). Pipe (Sass (). On (' Error ', Sass.logerror ). Pipe (Minifycss ()). Pipe (Gulp.dest ('./build/prd/styles/'));//post-compilation Output path});//3. Add a listener event to the Sass file modification gulp.task (' watch ' , function () {Gulp.watch ('./src/styles/**/* ', [' sass ');}); Gulp.task (' Default ', [' Watch ', ' webserver '],function () {Console.log (' All Task queue execution completed ');});

In this way, a simple Sass preprocessing task is configured, then we also add the task to Gulp.watch () to implement the automatic compilation (that is, modify the Sass file after the save, immediately perform sass preprocessing), Server with Gulp startup can implement Sass file modification save to see the effect in the browser, the next section describes starting the local server.

Webpack Pre-compiled sass/less

Also take sass as an example:

    1. Install a sass-loader and node-sass module in the project using NPM, which is used to load sass related files, which is used to compile sass files. Additional two modules, css-loader and Style-loader , are required to load CSS-related files, which are inline styles for filling CSS styles into HTML.

      $ npm Install Sass-loader node-sass css-loader style-sass-d

    2. Then make a simple configuration in the Webpack configuration file webpack.config.js

      module:{loaders:[{test:/\.css$/,//matches files ending in. css, if your project does not need to be deliberately not configured loader: ' STYLE!CSS '//Here Order must}, {test:/\.scss$/,// Match files ending with. Scss loader: ' Style!css!sass '}]}

As mentioned earlier, Webpack is loaded by the dependency of the file, so when the program from the main portal (JS file) entered, in the dependent resource file found in the Sass file, will use our configured Sass-loader to load, and then use Node-sass to parse the style file compiled into the normal CSS syntax, and then just use style-loader to configure the style inline style to HTML (here's the question, what's css-loader for?). I also do not understand, but do not add will be error, there is known can be a message to exchange a bit. This webpack completes the pretreatment of the sass.

Start the server

We all know that in front-end development, AJAX requests are required to start a server. Especially in the front-end separation idea, front-end development is no longer as overly dependent on back-end development as before, the kind of front-end test AJAX requests need to install a Tomcat or other server to start the server phenomenon has become a past style, Now we can use a front-end auto-build tool like Gulp to start a local server for testing, and no back-end programmers are clamped (joking, and the backend good communication to make the front-end development more convenient). So, let's take a look at how Gulp and Webpack do this.

Gulp starting the server

To start a local serve in gulp, you need only the following steps:

    1. Install a gulp-webserver module in the project via NPM

      $ NPM Install gulp-webserver-d

    2. The Gulp-webserver module is then introduced through the COMMONJS specification in the Gulp configuration file Gulpfile.js and is simply configured

      1. Introduce the Gulp-webserver module Varwebserver =require (' gulp-webserver ');//2. Configure the server Taskgulp.task (' webserver ', function () { GULP.SRC ('./'). Pipe (webserver ({host: ' localhost ', port:80,//browser automatically refreshes livereload:true,//display file directory directorylisting:{ Enable:true, Path: './'},}); /3. Configure the default taskgulp.task (' Default ', [' Webserver '],function () {console.log (' Start task queue execution completed ');})

    3. Start the server on the command line

      $ gulp

Startup success:

    1. Enter localhost to open the page validation in the browser address bar.

After these three steps, we started a server in gulp. There is a convenient configuration to start the local service in gulp, that is, the setting of the livereload:true property, the browser will automatically refresh the browser according to the changes of the resources in your project (if your Chrome browser settings This property after you modify the file and save the automatic refresh, It may not be supported by your Chrome browser, you can search for and install the Livereload plugin in the Chrome extension, for example:

My Gulp test directory structure:

Index.html

<! DOCTYPE html>

I enter the following in the App.js file, and then save it.

Console.log (' Gulp-webserver livereload ');

The information will be printed immediately on the console in the browser:

Indicates that the browser automatically refreshes the project, this small feature in our development has been tried. However, this feature needs to be combined with the gulp.watch() real-time monitoring file changes in the previous section, and then after the merge compression and sass/less compilation operations are performed, the browser is refreshed to ensure that we have modified the content. Therefore, the livereload:true property is only monitored after we modify the file after refreshing the browser to re-request the file, if we do not recompile the modified file, the browser gets to the original file, and will not show changes.

Webpack starting the server

In Webpack, you can also install a webpack-dev-server in the form of a plug-in to achieve the purpose of starting the local server, the following steps:

    1. Install a webpack-dev-server module in the project via NPM

      $ NPM install-g webpack-dev-server-d

    2. Then make a simple configuration in the Webpack configuration file webpack.config.js

      Module.exports = {devtool: ' eval-source-map ',//webpack Portal file Configuration entry: {app:__dirname + "/src/scripts/app.js",},// Webpack Export File Configuration output: {path: __dirname + "/prd/scripts/",//output file path configuration filename: "bundle.js"//output file name configuration},//local server configuration Devserver: {contentbase: __dirname,//the local server loads the page in the same directory port:8089,//the local service port configuration colors:true,//the output in the terminal is color historyapifallback:true,//do not jump inline:true//real-time Refresh}}

    3. Start the server on the command line

      $ webpack-dev-server

Then you'll see a lot of command-line output, just look to ensure that no error indicates success.

    1. Enter the localhost:8089 test in the browser address bar.

Webpack start the Local service also smooth implementation, is not also want to implement like Gulp browser automatically refresh it? Can the Webpack be realized? The answer is yes, Webpack official provides an auxiliary development tool, it can automatically monitor the files under the project, once the change save operation, the development server will automatically run the Webpack Packaging command, help us automatically repack the development of the code. Also, you can automatically refresh the browser and reload the resource if needed. In theory it seems like this, but the implementation seems to have a lot of restrictions, for example, the HTML file automatic refresh problem (Html-webpack-plugin plugin use always error), When the local server starts in the non-Output.path path is not automatic refresh and other problems, and so I learn to learn again, or have to know can leave a message to discuss.

And this auxiliary tool is webpack-dev-server , it mainly provides two functions: one is to provide the server service for the static file, the second is the automatic refresh and the hot substitution (HMR). So it is possible to achieve the same functionality as Gulp, just add it $ webpack-dev-server later --inline --hot . It is important to note that --inline there is an automatic refresh, and that there is a inline:true in the Devserver property in the second section that needs to be configured, but a --hot hot swap (Learn more about hot replacements, understanding Webpack-dev-server, WEBPA Ck-dev-server).

By comparison, it seems that the webpack-dev-server of Webpack is better than the gulp-server function of gulp. Because through the above can be seen Webpack-dev-server has two major functions: one is to provide server services for static files, and the other is automatic refresh (automatic refresh actually requires two steps: 1. After modifying a file, the file is automatically compiled {including merge compression or syntax compilation}, 2. Refresh the browser to request the latest compiled file) and hot Swap (HMR), while Gulp-server provides the ability to start the local server and the ability to automatically refresh the browser only, without the ability to automatically compile a file, This requires additional module implementations (described in the previous section, combined with Gulp.watch () to monitor file changes in real time and compile).

In addition, it is important to note that the actual development of Webpack-dev-server realized when the automatic refresh, and did not perform automatic compilation, but the modified content of the merge compression and other processing sent to the browser, and caused the phenomenon has been compiled, but by build/ Prd/scripts Directory of bundle.js (merge compressed output file) file, you can find that the content is not compiled (for Webpack or unfamiliar, a lot of problems waiting to be resolved).

Mock data

In the current thought of separation between the front and back end, the coupling between the frontend and the backend is getting smaller, and the only thing that needs to be closely connected is the definition of the pretext and the determination of the data format. Typically, before the project starts, the front and back ends identify the interfaces and data formats in the project (and, of course, the need for changes in the project needs to be established on a temporary basis), and then the front-end can mock the data themselves.

Gulp implementing mock data

The implementation of the mock data in Gulp is achieved by Nodejs the built-in FS module and the URL module, because gulp itself is nodejs based. Remember that mock directory in the directory structure in the first section, "Modular development"? That is .json the mock data directory used to store the files.

    1. Configuring the Gulp Gulpfile.js file
1. Introduce the FS and URL module varfs =require (' FS '); varURL =require (' url ');//2. Reconfigure the previous section of Servergulp.task (' webserver ', function () { GULP.SRC ('./'). Pipe (webserver ({host: ' localhost ', port:80, Livereload:true, directorylisting:{enable:true, Path: '). '},//mock data configuration middleware:function (req,res,next) {varurlobj = Url.parse (req.url,true); switch (urlobj.pathname) {case ' /pro/getpro ': Res.setheader (' Content-type ', ' application/json;charaset=utf-8 '); Fs.readfile ('./mock/list.json ', function (err,data) {///above List.json path uses relative path, absolute path foreground cannot get data res.end;}); Return;case '/web/getuser '://....return; } next (); } }));});

Specifically, the HTTP request is intercepted by Nodejs, and different data is returned based on the request URL to simulate the back end processing.

Webpack implementing mock data

Perfect in ...

Version control

For version control, we are in the development process, but also a more frequent use of features, especially when the development team is relatively large, this feature is more important. So how is gulp and Webpack implemented?

Gulp Implementing version Control
    1. Install the gulp-rev and gulp-rev-collector modules through NPM in your project, which is used to generate MD5 code files for files and resource files that are named by MD5 code, which replaces file names with MD5 codes.

      $ NPM Install Gulp-rev gulp-rev-collector-d

    2. Then make a simple configuration in the Gulp configuration file Gulpfile.js

      1. Introduce a module Varrev =require (' Gulp-rev '); Varrevcollector =require (' gulp-rev-collector ');//2. Version number control Gulp.task (' ver ', function () {GULP.SRC (cssfiles). Pipe (rev ())//generates MD5 code. PIPE (Gulp.dest ('./build/prd/styles/'))//rename file. Pipe ( Rev.manifest ())//JSON file that produces version information. PIPE (Gulp.dest ('./build/ver/styles/')); GULP.SRC (jsfiles). Pipe (rev ()). Pipe (Gulp.dest ('./build/prd/scripts/')). Pipe (Rev.manifest ()). Pipe (Gulp.dest ('./ build/ver/scripts/')); })//Modify the CSS and JS files in the HTML dynamically gulp.task (' HTML ', function () {GULP.SRC (['./build/ver/**/* ', './build/*.html ']). PIPE ( Revcollector ()). Pipe (Gulp.dest ('./build/'));})

Gulp implementation of version control is very convenient, the two task into the Gulp.watch (), you can modify the save file real-time automatic modification version of the function.

Webpack Implementing version Control

Webpack in need of version control CSS, JS file, but Webpack version control only to implement the CSS, JS file to add hash value way to name the file, modify the reference path file names need to be implemented manually.

But the implementation is really simple, just modify the output file names in the Output.filename and plugins in the Webpack.config.js configuration file.

Module.exports = {devtool: ' Eval-source-map ', entry: {app:__dirname + '/src/scripts/app.js ',}, Output: {path: __dirnam E + "/prd/scripts/", FileName: "[name]-[hash].js"//Modify Output filename}, plugins: [Newet ('./styles/[name]-[hash].css '),//Modify output file name ] }

This will solve the problem.

Component control

Component control should be placed in the modular section or before and after the section, but because really do not know how to compare, in fact, there is nothing to compare, put in the last.

Gulp and Webpack the management of their respective components is the use of NPM for component management, to learn more about the management of NPM components can be self-Baidu, or look at this article into a door "npm introduction."

Comparison of Gulp and Webpack

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.