Read the directory

  • Ideal front-end development process
  • What is a Gulp
  • Webpack came out of nowhere
  • conclusion

It’s a bit long, 1,800 words in all, and takes 18 minutes to read. Ha ha, no patience to poke me straight to the climax.

Ideal front-end development process

Before we talk about build tools, what is the desired front-end development process?

  • Write business logic code (e.g. Es6, SCSS, PUG, etc.)
  • Processing to browser-aware (JS, CSS, HTML)
  • The browser automatically refreshes to see the effect

Front-end development is constantly 123.. 123.. 123… The last two steps above (i.e., 2 and 3) should be automated, and front-end developers should only focus on step 1 — writing the business logic code.

The automation should be left to build tools, and popular front-end build tools are gulp and Webpack (some people say that WebPack is not a build tool, and I don’t think there’s any argument for that. I think it’s fair to say that WebPack is a build tool given what it can do right now). This article will not give an in-depth analysis of the concepts and content of Gulp and Webpack. Instead, we hope to study their advantages, shortages and application scenarios from a macro perspective, so as to clarify the confusing relationship between gulp and Webpack that has permeated the front-end circle for a long time.

What is a Build tool? A build tool is a program that automatically generates usable files from source code. The build process includes packaging, compilation, compression, testing, and other related processing of source code. Build tools are designed to automate the build process, freeing up our hands by avoiding the repetitive mechanical work that programmers can’t stand. Free your hands to do whatever you like.

What is a Gulp

Here’s what Ta’s website says:

Dedicated to automating and optimizing your workflow, Gulp is a toolkit for automating the painful and time-consuming tasks of your development work.

Think about the painful and time-consuming tasks in our daily development work.

  • In ES6, typescript scripts need to be compiled into browser-aware javascript
  • Style files written with SCSS, less need to be compiled into browser-aware CSS
  • Check code for written specifications and run unit and integration tests
  • The development environment with Sourcemaps is much easier to debug, and the browser automatically refreshes the code and sees the results immediately
  • Production deployment code needs to compress and merge static files and add file fingerprint control caches
  • blabla… More on your own

Gulp claims to help us automate, so how does he help us automate? That leads to a mouthful of awesome NodeJS.

Node background tips

Node enables the front-end Jser to work independently of the browser. In the past, we would either write JS embedded in the HTML page and open the HTML page in the browser to run JS, or write running code snippet in the browser developer’s Console panel. In short, without the browser host, our JS will not run. Node has removed the Console from the developer tool so that JS can be run directly from the browser in Node. This means that JS now has two hosting environments, a browser and a Node. Of course, Node is not Console in developer tools, that’s just an analogy. It is a JavaScript runtime environment based on the Chrome V8 engine. It functions like the Console panel, but provides a large number of useful apis. Node can be regarded as a front-end revolutionary innovation. The Node Package Manager (NPM) released with Node has become the world’s largest open source library ecosystem. The combination of Node/NPM ushered in a big explosion of front-end ecology, a time to solve various problems of node packages emerge in an endless stream, bloom everywhere. Gulp is a small node package that goes through five passes and six passes.

With that out of the way, let’s see if Gulp is faking it, and if he can help us automate it.

As a Node package, the standard way to open it is of course:

npm i -g gulp
 Copy the code

Install the node package used to compile less:

npm i --save-dev gulp gulp-less
 Copy the code

Gulp -g is installed globally to execute the gulp task you wrote, namely gulp yourTask. The latter –save-dev is a local installation that allows us to write tasks using the GULp API, such as gulp.src(), gulp.task(), gulp.dest(), etc. It is possible to use the globally-installed GULp API directly, but it is strongly not recommended because of the gulp versioning issues involved and because using the globally-installed GULp API will create environment dependencies (assuming that the environment has gulp installed globally, if not, the application will fail).

Then create a new gulpfile.js file in the root directory of the project, which is the default gulp configuration file.

Gulpfile.js must be placed in the project root directory? You can also put it in a different directory, but that would require manually specifying the gulp configuration file gulp yourTask –gulpfile yourGulpfilePath when starting the gulp task. You might also need to install gulp-CLI globally, so unless you need to, Otherwise, just put it in the project root directory, which is the easiest. Must the name of the configuration file be gulpfile.js? Js is case insensitive and gulp will recognize gULPFile as long as toLowerCase is followed by gULPFile. If toLowerCase is named after gULPFile, you will have to use — gULPFile again.

The project directory structure now looks like this:

Build the pre-GULP project directory structure

The next step is to write a gulp task in gulpfile.js (gulp calls each painful and time-consuming task a task) :

const gulp = require('gulp');
const less = require('gulp-less');

gulp.task('build:less', function(){
    return gulp.src('./src/*.less')
        .pipe(less())
        .pipe(gulp.dest('./dist'));
});
 Copy the code

Finally, open a terminal and run gulp build:less in the terminal. Ok, the compiled file has been exported to the dist directory:

The post gulP project directory structure is constructed

Now that you’re a Gulp expert, that’s basically what Gulp is all about. How about that? Simple enough, silky enough. This is what makes Gulp great – it’s easy to learn, easy to use and a five-minute pro. If you want to perform other painful and time-consuming tasks, simply download and install the corresponding gulp plug-in package, and then write a gulp.task.

How the source code is processed usually doesn’t matter, because the gulp package does it for you, and it’s beautifully packaged. You just tell Gulp what you want, and gulp and its plug-ins take care of it for you. It’s like you have an electronic document transfer into the printer, tell it I’d like a A4 paper printing, yi yi yi ~, the printer will spit out a piece of A4 paper, it is your document content. The source code is your digital document, the gulp plugin is your printer, and the usable files you generate are the A4 paper in your hand. You don’t need to care about how the printer works inside because it’s packaged well, or you can take the printer apart to see what’s going on. Gulp is stream-based? Stream is not a gulp creation, but an I/O mechanism that has been in use since the Unix era and is still widely used today. Node encapsulates a stream module for operating on streams. The stream on which gulp is based is a stream wrapped by Node. The pipe method in the gulp.task() code above is not a gulp API, but a Node API, specifically a Stream API. How to do this: The return value of gulp.src() is an instance of Node Stream. Pipe calls the pipe method of this instance, and pipe returns an instance of Node Stream. Implement the previous.pipe().pipe().pipe() concatenation. Those familiar with jQuery should be familiar with this technique.

Webpack came out of nowhere

Gulp seems to be the perfect solution to every painful and time-consuming task of front-end development. However, the front end is growing faster than expected, and the page performance and user experience are so demanding that some areas of Gulp, especially large spAs (single-page applications), seem inadequate:

  • The core of single page application is modularity. Before ES6, JavaScript language itself has been without module system, leading to AMD, CMD, UMD various wheel modularity schemes have jumped out. Gulp is helpless against this modularity mess, and the gulp plugin has no idea what to do with it. But it’s understandable that modular solutions are not for everyone. There are too many issues to consider;
  • The cutting-edge SPA technology gulp is a bit weak to handle, such as Vue’s single-file components, gulp with some plug-ins can handle, but poorly. In fact, in the final analysis, or the lack of modular processing;
  • An important rule for optimizing page loading speed is to reduce HTTP requests. Gulp only streams static resources and does not optimize and integrate them effectively. This means that gulp ignores the system level. There is still a lot of room for optimization in this area, especially on mobile devices. Traffic? Pay)? It’s more than you can imagine. Don’t tell me about Gulp-concat or CSS Sprites. They’re fine for small things, but not for large applications. With pages that have hundreds of fragmentary resources (images, stylesheets, scripts), in other words, hundreds of HTTP requests, this optimization needs to be urgent. Here’s how reducing HTTP requests can effectively reduce page load timestamps.
  • blabla… You can see for yourself, the main drawback is the large single-page application;

A hero is known in the time of misfortune. With a roar, Webpack dug up Gulp’s corner in a big way.

Old rules, first look at the Webpack official website how brag force introduce yourself:

Webpack is currently the most popular front-end resource modular management and packaging tool. It can package many loose modules according to dependencies and rules into front-end resources suitable for production deployment. You can also split up the code for modules that are loaded on demand and load them asynchronously when they are actually needed.

Is not to see a face meng force, unknown sense li. In my eyes, everything is a module. Webpack’s concept of “everything module” is a perfect match for SPA. This is also the main reason why Webpack became famous in a short period of time and directly shook gulP’s position.

Webpack is a bit of an avant-garde concept, and it brings with it a lot of new concepts and content, such as loaders, Dependency Graph, and so on. Compared to the difficulty of learning Gulp in two hours, you may still feel dizzy after two days of study.

Let’s take a quick look at the main ways WebPack works.

Webpack, like gulp, is a small Node package.

npm i -g webpack
npm i --save-dev webpack
 Copy the code

As with gulp, global installation is to perform Webpack tasks and local installation is to use the API provided by WebPack.

After installing Webpack, create a new webpack.config.js file in the root directory of the project. This is the default configuration file for Webpack, which is similar to the function of gulp’s gulpfile.js. Webpack.config. js is also case-insensitive, and webpack will recognize it if you call it webpack.config.js, but if you call it something else or put it in a different directory, you need to specify the configuration file using the –config option.

The current project directory structure is as follows:

Pre-build WebPack project directory structure

The next step is to configure the required options in webpack.config.js. Note that the important difference between Webpack and gulp is that the use of webpack has changed from programmatic to configurational:

const path = require('path'); Module.exports = {entry: './ SRC /index.js', // tells webpack which file you want to compile. Output: {// tells Webpack where to put the generated file. 'bundle.js', path: path.join(__dirname, 'dist') } };Copy the code

In the end, again similar to gulp, you run WebPack in a terminal (which usually displays a large pile of compilation information). Ok, now WebPack has exported the compiled files to the dist directory:

Build the post-WebPack project directory structure

See if this is confusing, and Webpack has already done it before you know what’s going on. This is an important difference between the way WebPack and Gulp work: Gulp builds a platform on which the gulp plugin performs and does all the specific work related to the build. And Webpack on cattle force, Webpack first built a platform, and then their own singing hi in the above, a careful listen, he is singing “we are not the same”, of course, he is also let Webpack plug-in in the above singing opera.

That is to say, Webpack encapsulates many functions into its own body, making it powerful and bloated. Now you can write ES6 code directly in./ SRC /index.js, because WebPack has wrapped the work of compiling ES6 into its own implementation, making webPack seem to support ES6 natively without the need for third-party plug-ins. It actually uses third party mods internally, so you don’t have to go to the next Babel plugin to translate ES6. The advantage of this encapsulation is that it is very easy to use, but the disadvantage is that the user has no idea what is going on and is completely confused when it is finished.

This is just the simplest example of webPack use, and it’s not even “Hello World.” For details on how to package typescript, style sheets, images, fonts, and so on, go to the WebPack website to learn more.

Webpack’s “all modules” feature perfectly solves several shortcomings exposed by GULP. Even webPack’s official website says that it decided to build a module packer suitable for large SPA applications because existing module packers are not suitable for large SPA applications. In other words, Webpack is made for large spas.

How does WebPack implement streaming of large amounts of source files like Gulp? Webpack was never intended to do this. Webpack is not intended to replace GULP, but rather to provide a better build solution for large spAs. Streaming a lot of source files is something Gulp is good at, and WebPack doesn’t want to, and doesn’t need to. Even if we rob it, it’s just a crappy gulp. Since webpack modularity is so strong, after that modularity will all use Webpack good Webpack modularity is strong, but he fat ah, not everyone can move, mainly he in order to provide more functions packaged into too many things, so the choice or need to adjust to local conditions. If you simply package JS (which is often the case for multi-page applications), you can use small, beautiful implementations like Rollup and Browserify because they only do one thing — package JS. If you need to pack all the static resources like images, styles, fonts, etc., Webpack is definitely the first choice. This is why more and more popular libraries and frameworks are moving from WebPack to rollup packaging, because they only need to package JS, and webPack has many powerful features that are not used at all. Even the rollup website says that if you’re building a library, rollup is the best choice, but if you’re building an application, go for WebPack.

conclusion

I’m optimistic that gulp and Webpack are not the same thing. I don’t think so, although the starting point is different. Gulp is streaming and WebPack is module, but the goal is the same. That is to promote automation and engineering management of the front end. So far, WebPack has grown so powerful that it can do almost everything gulp can do in terms of building, and it can do everything That Gulp can’t. Gulp and WebPack can solve the same painful and time-consuming tasks of development, but in a very different way.

The following table compares Gulp and Webpack from various angles:

Gulp Webpack
positioning A flow-based automated build tool A versatile module packer
The target Automated and optimized development workflow for the development of general website General-purpose module package loader, designed for large SPA applications on mobile terminals
Learning difficulty Easy to learn and easy to use, the API has only five methods in total There are plenty of new concepts and apis, but the good news is that they are well documented
Applicable scenario The flow-based approach is suitable for multi-page application development The feature of everything module is suitable for single page application development
practices The js, TS, SCSS, less and other source files input (gulp.src) are bundled, compiled, compressed, renamed, and then output (gulp.dest) to the specified directory, and packaged for construction The dependency graph is generated by recursive parsing of entry files, and then all dependencies are packaged together. Before packaging, all dependencies are translated into packable JS modules, which are built for packaging
use Regular JS development, writing a series of build tasks. Edit various JSON configuration items
advantages Suitable for multi-page development, easy to learn, easy to use, elegant interface. It can package all resources and adapt to various module systems
disadvantages Weak output in single-page applications and somewhat difficult to handle with popular single-page technologies (e.g. Vue single-file components are difficult to handle using gulp, while Webpack is easy to handle with one loader) Not suitable for multi-page application development, high flexibility but complicated simultaneous configuration. This “wrap everything” advantage is especially important for HTTP/1.1, because all resources packaged together significantly reduce the number of resource requests when a browser visits a page, thus reducing the time an application must wait. However, this advantage may become less prominent as HTTP/2 becomes more popular, because HTTP/2 multiplexing can effectively solve the bottleneck problem of parallel client requests.
conclusion Browser multi-page application (MPA) preferred solution Browser Single page application (SPA) preferred

Why doesn’t Gulp integrate webpack, since it’s all open source Tencent? Why doesn’t gulp integrate Alibaba? Integration should be impossible because gulp and Webpack are positioned differently. Therefore, there is no one-size-fits-all solution. Only by analyzing specific problems and choosing suitable solutions can the problem be solved correctly. Gulp and Webpack are just tools to solve our problems. Don’t let them hold you back. As you can see, both of these tools have their advantages and disadvantages. The two gay friends are not mutually exclusive, but complementary, and no one will be shot to death on the beach.