Gulp
What is Gulp?
Gulp is a stream-based build tool that automatically performs specified tasks, succinctly and efficiently
What can Gulp do?
- In a development environment, you want to be able to organize code by module and listen for changes in real time
- CSS/JS precompilation, postCSS and other schemes, browser prefix automatic completion and so on
- Conditions output different web pages, such as APP page and mobile page
- In an online environment, I want to merge and compress HTML/CSS /javascritp/ images to reduce network requests and reduce network load
- And so on…
Install Gulp
npm install -g gulp // Global installation
npm install --save-dev gulp // Install to the current project and add dependencies to package.jsonCopy the code
Core API Introduction
gulp.task task(name[, deps], fn)
The task() method is used to define a task by passing in a name, an array of dependent tasks, and a function. Gulp executes the array first and then calls the defined function to control the execution of the task.
Example: To define a task build to perform CSS, JS, and IMGS tasks, we can do this by specifying an array of tasks instead of a function.
gulp.task('build'['css'.'js'.'imgs']);Copy the code
gulp.src src(globs[, options])
The SRC () method takes a glob or an array of globs and returns a data stream that can be passed to the plug-in
Gulp uses node-glob to retrieve files from the glob you specify:
-
app.js
An exact match -
*.js
Files that match the js suffix -
**/*.js
Matches js files in multiple levels of directories (including the current directory) -
! js/app.js
Precise ruled out
Example: the js directory contains compressed and uncompressed JS files. We want to compress files that have not been compressed
gulp.src(['js/**/*.js'.'! js/**/*.min.js'])
Copy the code
gulp.dest dest(path[, options])
The dest() method is used to write files, with the first argument indicating the directory name for the final output. Note that it does not allow us to specify the file name of the final output, only the output folder name, which is created automatically if the folder does not exist.
Example: Export js files from the development directory SRC to the deployment directory dist
gulp.src('src/**/*.js')
.pipe(gulp.dest('dist'))Copy the code
gulp.watch watch(globs[, opts], cb) or watch(globs[, opts], tasks)
The watch() method listens for files, takes a glob or glob array and an array of tasks to perform callbacks // when the templates file in the templates directory changes, and automatically executes the compile task
gulp.task('watch'.function (event) {
gulp.watch('templates/*.tmpl.html'['artTemplate']);
console.log('Event type: ' + event.type); // added, changed, or deleted
console.log('Event path: ' + event.path); // The path of the modified file
});
Copy the code
Another nice feature of gulp.watch () is that it returns a Watcher object
- Watcher objects can listen for many events:
- Change Triggered when a file changes
- End fires when watcher ends
- Error Is raised when an error occurs
- Ready fires when a file has been found and is being listened on
- Nomatch fires when a glob doesn’t match any files
- The Watcher object also contains some methods that can be called:
- Watcher. End () to stop the watcher
- Watcher.files () returns a list of files that Watcher listens on
- Watcher.add (glob) adds the file matching the specified glob to watcher (optional callback is also accepted when the second argument is used)
- Watcher. Remove (filepath) Removes individual files from Watcher
The task will match all the files to js/*.js, execute JSHint, print out the result, unindent the files, and merge them as build/app.js, as shown below:
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat');
gulp.task('js'.function () {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(uglify())
.pipe(concat('app.js'))
.pipe(gulp.dest('build'));
});Copy the code
Webpack
What is Webpack?
Webpack is a modular management tool, which can compress, preprocess, pack on demand, load on demand and so on.
What are the important features of WebPack?
Plug-in: WebPack itself is very flexible and provides a rich plug-in interface. Based on these interfaces, WebPack has developed many plug-ins as built-in features. Fast: WebPack uses asynchronous IO and multi-level caching. So Webpack is fast, especially for incremental updates. Rich Loaders: Loaders are used to preprocess files. This way WebPack can package any static file. High compatibility: WebPack supports both AMD/CommonJs/ES6 module solutions. Webpack statically parses your code and automatically manages its dependencies for you. In addition, WebPack is very compatible with third-party libraries. Code Fragmentation: WebPack can shard your code for on-demand packaging. This mechanism ensures that the page only loads the REQUIRED JS code, reducing the time for the first request. Optimizations: WebPack provides many optimizations to reduce the file size of the packaged output, and it also provides a hash mechanism to solve browser caching problems. Development mode friendly: WebPack also provides many ancillary features for development mode. Examples include SourceMap, hot updates, etc. Multiple application scenarios: WebPack applies not only to Web application scenarios, but also to Webworkers and Node.js scenarios
How is WebPack best configured?
Webpack’s official configuration method is to return a JSON via module.exports, but this scenario is inflexible and does not fit many scenarios. For example, to solve: Production mode and development mode, webpack configuration is different, there are roughly two ideas. 1, two configuration files webpack. Config. Production. Js/webpack config. Development. Js, then different scenarios, use different configuration files. Module. exports returns a function that accepts arguments.
Comparatively speaking, the first one is simpler, but has a lot of reconfiguration. The second option is more flexible and recommended. So, the configuration code shelf as a return function looks like this:
module.exports = function(env) {
return {
context: config.context,
entry: config.src,
output: {
path: path.join(config.jsDest, project),
filename: '[name].js'.chunkFilename: '[name].[chunkhash:8].js'.publicPath: '/assets/' + project + '/'
},
devtool: "eval".watch: false.profile: true.cache: true.module: {
loaders: getLoaders(env)
},
resolve: {
alias: getAlias(env)
},
plugins: getPlugins(env)
};
}
Copy the code
The key configurations are briefly described here, and will be covered in detail at each point in a future series of blogs. Context: indicates the context. Entry: The entry file, which is the entry for all dependencies. Webpack starts from this entry static parsing, analyzing dependencies between modules. Output: packages the output configuration. Devtools: SourceMap option for easy debugging in development mode. Watch: Monitor mode, incremental update, development essential! Profile: Optimization. Cache: Webpack builds a lot of temporary files. If you open the cache, these temporary files will be cached for a faster build. Module. loaders: As described earlier, loaders is used to preprocess files. This way WebPack can package any static file. Resolve. Alias: A module alias to make it easier to reference the module. Plugins: As mentioned earlier, some of the built-in features of WebPack are provided as plug-ins.
Difference between Webpack and gulp
Gulp is a stream-based build tool: an all in One package that outputs a JS file and a CSS file, with the advantage of reducing HTTP requests. Webpack is a modular management tool, using Webpack modules can be compressed, preprocessed, packaged, load on demand and so on.
Related interview questions
1. What about gulp?
Gulp is an automated construction tool, a front-end engineering development tool, enhance the development process, easy to use;
Gulp = require(‘gulp’)
Workflow is defined through the default task, and gulP is executed at the terminal to automate the operation
NPM install gulp-cli -g // NPM global installation gulp NPM init // Create a package.json file in the root directory of the projectCopy the code
In the project root directory, create gulpfile.js:
let gulp = require("gulp");
gulp.task("default".function() {// Define a task named default console.log()"this is default task"); });Copy the code
The API is very simple and there are only four
- Gulp. Task Create task: parameter task name, array of pretasks, callback function
- Gulp.src Find files: Find one or more files by path
- Gulp. dest prints to the specified directory: if not, create a new one
- Gulp. watch listens for file changes and executes tasks
- Pipe is not clear, but all execution conditions except gulp.src should be placed in.pipe()
Webpack vs. Gulp
Gulp is a front-end automation tool that standardizes the front-end development process and implements front-end separation, modular development, version control, file consolidation and compression, mock data, etc. “Gulp is like an assembly line of products. The whole product starts from scratch and is controlled by the assembly line. On the assembly line, we can manage the product.” In addition, Gulp builds the entire development process through Task.
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 code separate modules that are loaded on demand and load them asynchronously when they are actually needed. Through loader conversion, any form of resources can be regarded as modules, such as CommonJs module, AMD module, ES6 module, CSS, images, JSON, Coffee, LESS, etc.
Comparison of Gulp and Webpack features: Compare Gulp and Webpack from eight aspects: basic concept, start local Server, SASS /less precompilation, modular development, file merge and compression, mock data, version control, and component control.
The basic concept
First, conceptually, it is clear that the focus of Gulp and Webpack is different.
Gulp focuses on the control and management of the whole process of front-end development (focusing on pipeline). We can configure different tasks for Gulp (through Gulp’s gulp.task () method configuration, For example, start serve, sass/less precompilation, file consolidation and compression, etc.) and let Gulp implement different functions to build the whole front-end development process.
Webpack is called module packing machine, which can be seen that Webpack focuses more on module packaging, of course, we can put all resources in the development (pictures, JS files, CSS files, etc.) can be regarded as modules. Webpack itself was originally designed for front-end JS code packaging, and has since been extended to other resource packaging. Webpack handles resources through loaders and pluging.
In addition, we know that Gulp controls the whole process, so every task configured in its configuration file (gulpfile.js) can manage all resources in that task’s configuration path in the project.
Modular development
The so-called modular development, my understanding is, in the development, the different development files according to his specific purpose for classification management, in the use of CommonJ, AMD, CMD, these resource files according to certain requirements for compression coupling and version control processing.
Maybe this understanding or hair is debatable, but personally I think modularity is the management of content, is to understand coupling.
What if the WebPack package is too large?
Webpack packs all of our files into a single JS file, so even if you’re a small project, the packed file will be very large. You can optimize from the following aspects: removing unnecessary plug-ins, extracting third-party libraries, code compression, code segmentation, and caching.