In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use Gulp to build a simple front-end automation project", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Gulp to build a simple front-end automation project.
Preparatory work
Install Node
First of all, Gulp is based on Nodejs, so installing Nodejs is a prerequisite. Node can be said to be a front-end artifact. There are a variety of tools based on Node, precisely because these tools make it very convenient for us to build front-end projects.
Change the default installation location of the Node plug-in (optional)
I generally don't like too many things that have nothing to do with the system in C disk, and the plug-ins installed through Node's own npm are installed on C disk by default, but after I install Node to disk D, I want to install the plug-in in the home directory of Nodejs. What should I do?
Create two new folders "node_global" and "node_cache" under the Node home directory
Start cmd and enter the following settings directory to change npm config set prefix "D:\ Program\ nodejs\ node_global" npm config set cache "D:\ Program\ nodejs\ node_cache" according to your directory structure.
Close cmd and open the system dialog box, "my computer right-click Properties"-"Advanced system Settings"-"Advanced"-"Environment variables".
Go to the environment variable dialog box, create a new "NODE_PATH" under the system variable, and enter "D:Programnodejsnode_globalnode_module". As a result of changing the default address of module, the above user variables have to be changed (the user variable "PATH" is changed to "D:Programnodejsnode_global"), otherwise using module will lead to the error of "xxx is not an internal or external command, nor is it a runnable program or batch file".
After these four steps of setup, you can put the installed Node plug-in in the home directory of Nodejs.
Install Gulp
/ / Global install Gulp npm install-g gulp / / install Gulp npm install-- save-dev gulp in the project
Run gulp-v. If no error is reported, the installation is successful.
Then run it on the command line
Npm init
Let the project produce package.json files
Construction project
As we all know, in the development project, there are two processes: development and online. In development, we generally need automatic refresh and real-time compilation, but if we go online, we need to consider a lot of optimized things, such as file compilation and compression, static resources slow storage processing and so on. My own project only involves file compilation and compression, real-time refresh, static resources slow storage these three basic processes.
The directory structure of the project is as follows
-project | |-dist (the folder is generated by packaging) |-css |-index-9dcc24fe2e.css |-js | | index-9dcc24fe2e.js | |-index.html | |-src |-scss |-index.scss |-- | -js |-index.js |-index.html |-gulpfile.js |-package.json
The process used for development
File compilation
In the project, you are going to use scss as the precompilation of css, so you need to use gulp to compile scss, so install gulp-sass first.
Npm install-save-dev gulp-sass
After the installation is complete, refer to the configuration directly in gulpfile.js
Const sass = require ('gulp-sass'); / / scss compile gulp.task (' scss:dev', () = > {gulp.src ('src/scss/*.scss') .pipe (sass ()) .pipe (gulp.dest (' dist/css')); / / put the generated css file under the dist/css folder})
Here is a brief introduction to the two api of gulp:
Gulp.src () enter a file that matches the provided matching pattern or an array of matching patterns. A stream will be returned or can be piped to another plug-in. Read the file
Gulp.dest () can be entered by pipe and will write a file. And emits all the data, so it can be pipe to multiple folders, and will be created automatically if the folder does not exist. Write a file
Real-time refresh
There are many tools to achieve real-time refresh, I use browser-sync myself, this tool is very powerful, to learn more about its usage can see the official website: http://www.browsersync.cn/.
First, we install the module in the project.
Npm install-save-dev browser-sync
According to the configuration of browser-sync and gulp on the official website, the configuration is as follows:
Const browserSync = require ('browser-sync') .create (); / / Refresh const reload = browserSync.reload Gulp.task ('dev', [' scss:dev'], function () {browserSync.init ({server: {baseDir:'./' / / set the root directory of the server}, logLevel: "debug", logPrefix: "dev", browser:'chrome', notify:false / / enable silent mode}) / / use the listening function of gulp to implement the compiled and modified file gulp.watch ('src/scss/*.scss', [' scss:dev']); gulp.watch (('* .html')) .on ('change',reload);})
In this way, a simple gulp development process comes out, just a compiled scss and a real-time refresh.
Package and launch all processes
Packaging online, we are more concerned about static resources anti-caching, optimization. For the compression of css,js and the processing of pictures, the simple process I wrote does not involve the processing of pictures, so here is only for css,js,html processing.
We can use gulp-sass to compress css, because it has a configuration option to directly output the compressed css when compiling scss. I used gulp-uglify to compress js and gulp-rev and gulp-rev-collector for static resource anti-caching.
The treatment of css,js
/ / scss compiles gulp.task ('css' () = > {gulp.src ('src/scss/*.scss') .pipe (sass ({outputStyle:' compressed' / / compile and output the compressed file})) .pipe (rev ()) / / add a hash to the css .pipe (gulp.dest ('dist/css')) .pipe (rev.manifest ()) / / add a hash file to the list. pipe (gulp.dest (' rev/css')) }) / / compress js gulp.task ('js' () = > {gulp.src ('src/js/*js') .pipe (uglify ()) .pipe (rev ()) / / add a hash to js. Pipe (gulp.dest (' dist/js')) .pipe (rev.manifest ()) / / add a hash to pipe Add the desired file to the list. pipe (gulp.dest ('rev/js')) })
Where gulp-rev adds a hash value to the css file name, and rev.manifest () generates a json file, which records a correspondence between the original file name and the file name after adding the hash value, which will be used when * corresponds to a reference to replace the html.
The generated json file is as follows:
{"index.css": "index-9dcc24fe2e.css"}
Because the hash value is added to the file, the css and js compiled each time are different, which will result in a lot of redundant files, so we can empty the original file every time before generating the file.
There is also a plug-in to do this in gulp-gulp-clean, so we can empty the original text before compiling the compression to add a hash.
Empty the generated project file
Const clean = require ('gulp-clean'); / / empty all files in the folder / / empty the original folder gulp.task (' clean', () = > {gulp.src (['dist',' rev'], {read: false}) / / the dist set here deletes the dist folder and all its files. Pipe (clean ());})
Let the files that add hash code be automatically added to the html
The previously mentioned gulp-rev implements to add a hash code to the file name, but how to automatically change the reference that did not add a hash value into a reference that has already added a hash value after the packaging is completed. Here, a plug-in gulp-rev-collector of gulp-rev is used. The configuration is as follows:
/ / css to be processed Js introduces html gulp.task ('reCollector', () = > {gulp.src ([' rev/**/*.json','src/*.html'])) .pipe (reCollector ({replaceReved: true, / / whether the files that have been replaced in the template can be replaced again. The default is false dirReplacements: {/ / identifies the collection of directory replacements. Because the manifest file created by gulp-rev does not contain any directory information, 'css/':' / dist/css/', 'js/':' / dist/js/'}) .pipe (gulp.dest ('dist'))})
There is no normal replacement?
When I wrote it myself, there was this problem. After running the task, the css and js references in html did not change. After searching the Internet for a long time, I found out that it was because I used the gulp-rename plug-in, and then added .min to the file name (as for why, just because it was compressed, I should write it), but the file referenced in the html I wrote did not have .min. Because gulp-rev-collector in the replacement according to the generated json file replacement, in json, the files have .min but not in html, so can not match, naturally can not achieve the replacement, so in the replacement must pay attention to the gulp-rev generated in the json file of the css,js and html references are the same, otherwise the replacement cannot be achieved.
There is a revSuffix in gulp-rev-collector 's api, which seems to achieve a function similar to gulp-rename, but I don't know how to use it. Please let me know if you know.
Perform all tasks
After completing the above steps, we string all the tasks together so that they can be executed with one command and then all.
Gulp.task ('build', [' clean', 'css',' js', 'reCollector'])
Understand gulp again
Is the task of gulp--- executed sequentially?
I thought that when I came here, even if I had finished writing, running, *, packaging and generating files, and running it again, I reported an error!
[19:04:57] Finished 'default' after 7.38 μ s stream.js:74 throw er; / / Unhandled stream error in pipe. ^ Error: ENOENT: no such file or directory, stat'd:\ project\ dist\ js\ index-6045b384e6.min.js' at Error (native)
Prompted that I could not find this file, which made me very depressed, and then I executed separately, very ok, and could be sure that there was a problem with the execution order, probably after the execution was not completed. I checked the gulp's official website documents to know that its gulp pipe was carried out by a task and was synchronized, but each task was out of sync, which verified my conjecture. So find out how to solve this problem online and find a npm plug-in called run-sequence. The configuration file is as follows:
/ / package and launch gulp.task ('build', () = > {runSequence (' clean', ['css',' js'], 'reCollector');})
I thought it would be ok, but as a result, it still reported an error. Here is another understanding of gulp.
Run-sequence plug-in's handling of Asynchronous tasks
After using this plug-in to make the task proceed in an orderly manner, I want to see its serialization of the task more visually. I wrote a demo like this:
Gulp.task ('axiaojiaqingfunction () {setTimeout (function () {console.log (1);}, 30);}); gulp.task (`bounded dint function () {console.log (2);}); gulp.task ('ab',function () {runSequence (`axiaozhongb');})
But there is a problem here, runSequence does not work, look for plug-in instructions and gulp official documents, the original asynchronous tasks, such as setTimeout,readFile, need to add a callback execution, where callback () will return a promise resolve (), telling the following task that the current task has been completed, and later can continue to execute, so execute callback in task a.
Gulp.task ('axiaojinjingfunction (cb) {setTimeout (function () {console.log (1); cb ();}, 30);})
So why don't the tasks written above need to add a callback? Because gulp's pipe flow allows small tasks (each pipe) in each task to be executed sequentially, so the entire pipe flow is synchronous, not asynchronous, so there is no need to manually return it to promise,run-sequence to automatically manage it for us.
At this point, I believe you have a deeper understanding of "how to use Gulp to build a simple front-end automation project". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.