Yeoman+bower+gulp Web front-end Automation workflow (beginner tutorial)

Source: Internet
Author: User
Tags globs

Yeoman includes three parts yo (scaffolding tool), GRUNT/GULP (build tool), Bower (Package Manager). I heard gulp is easier to get started, so I didn't use grunt to choose Gulp What is the development process?

It seems to me that a complete development process should include:

    • Initialization of the local development environment
    • Third-party dependent management
    • Source file Compilation
    • Automated testing
    • Publish to pipeline and various environments

The modern development process is to make the above parts can be automated, a command can make these processes are automatically completed, and quickly get errors or through the feedback, so that we can quickly fix errors and release.

Tools Simple Introduction Scaffolding tools (Yeoman official website http://yeoman.io/)

Scaffolding is to help you reduce the " repetitive work to reduce repetitive work" tool, it is like if you want to start a new small project, originally you may need at least manually create a JS, CSS, images three folders it? and scaffolding tool is to help you each new project to execute this action process part of the tool, that is, you need a line of command, do not have to manually create folders and structure.

However, you may have to think about it, I do not have the directory structure of each project to be one, what should be done? It is necessary to install different generator depending on the project (http://yeoman.io/generators/), of course, you can also customize a generator, and then publicly for others to use, now we just learn how to use other people's generator , I will not customize it, this custom problem please do your own Baidu Tutorial bar! Ha ha

Build tool (Gulp Chinese web address http://www.gulpjs.com.cn/)

Gulp is the front-end development process of the code to build the tool, is the construction of automation projects, the simple is that you put a set of what compression, merge these rules in advance to write, and so you write the code, just a line of command can be generated on-line code, and then directly uploaded to the server is good, Of course you can also have more advanced use, follow your own research.

Package management tool (Bower website address https://bower.io/)

Bower is a client-side technology Package Manager that can be used to search, install, and uninstall network resources such as JavaScript, HTML, and CSS. For example: JQuery, Bootstrap

Specific installation process

Ready to work you should have installed Nodejs, NPM, right? Do not install, please self-installed Baidu, download the installation package-double-click-next-> installation Completed

Global installation Yeoman, gulp, Bower

npm Install yo gulp-cli bower-g

If the execution of this command is not an error, then congratulations, the basic environment has been set up, the rest is required according to your project, and then follow the generator, temporarily create a WebApp project as an example, so we first install a Generator-webapp

NPM install-g Generator-webapp

After installing Generator-webapp, directly under the project directory

You can create a WebApp project. This is done, and then you can write the code quietly.

Attached: (gulpfile.js configuration file and index.html personal understanding)

Index.html

<!--build:css Styles/main.css--    <link rel= "stylesheet" href= "Styles/main.css" >    <!-- This link is your development time page reference CSS path, the above build:css is the build time to store the path and name, the path and name can be customized, the following JS principle--    <!--endbuild--

Gulpfile.js

/*//Import Toolkit require (' Node_modules module ') var gulp = require (' Gulp '),//local installation gulp where less = require (' gulp-less '); Define a testless task (custom task Name) gulp.task (' Testless ', function () {gulp.src (' src/less/index.less ')///file for the task. Pipe (Le SS ())//module called by the task. Pipe (Gulp.dest (' src/css ')); INDEX.CSS} will be generated under SRC/CSS); Gulp.task (' Default ', [' testless ', ' elsetask ']); Define default task Elsetask for other tasks, the example does not define Elsetask task//gulp.task (name[, Deps], fn) define Task Name: Task Name Deps: Dependent Task name fn: callback function//gulp.src ( globs[, Options]) perform task processing file globs: File path processed (string or array of strings)//gulp.dest (path[, Options]) after processing the file generation path *///generated on 2016-08- The Using Generator-webapp 2.1.0const Gulp = require (' gulp ');//Can be bulk require Package.json in the Devdependencies plugin, do not have to import a const Gulploadplugins = require (' gulp-load-plugins ');//browser automatically refreshes plugin const Browsersync = require (' Browser-sync ');//delete files and folders const DEL = require (' del ');//WIREDEP solves the problem of introducing HTML into the Bower Front end Library const WIREDEP = require (' WIREDEP '). stream;//Local Development agent cross-domain request with plug-ins const Proxymiddleware = require (' Http-proxy-midDleware '); const $ = gulploadplugins (); Const RELOAD = browsersync.reload;//Define the proxy rules for the following creation of service usage to/service/ Start with the proxy to the target domain under const proxy= proxymiddleware (['/service/'],{target: ' http://xxx.xxxx.com ', changeorigin:true});// Compile sassgulp.task (' Styles ', () = {return gulp.src (' app/styles/*.scss ')//plumber is an error handling plug-in that, when an error occurs, does not immediately go to the main, but into the plumb Er to prevent the program from running. Plumber can prevent the Gulp plug-in error from causing the process to exit and output the error log: pipe ($.plumber ())//sourcemaps is a plug-in used to generate a mapping file, and the map file records the process of compiling from Sass to CSS, each The line's Sass code corresponds to which line of CSS code.     In the SCSS compile process, add the mapping relationship, you can easily debug,//in the file stream requires two statements://***plugins.sourcemaps.init ()//If you want to output Sourcemaps file, you can add a path in the write (path); Plugins.sourcemaps.write (). Pipe ($.sourcemaps.init ())//sass is the core of the compiled Sass plug-in, specifying the output format expanded,precision specified    The precision of how many bits are used when outputting a decimal number, and then the path and error log are specified. Nested output mode nested//expansion output mode expanded//compact output mode Compact//compression output mode compressed. Pipe ($.sass.sync ({outputsty    Le: ' expanded ', Precision:10, includepaths: ['. '] }). On (' Error ', $.sass.logerror))//add browser prefix. pipe ($.autoprefixer ({browsers: [' > 1% ', ' last 2 versions ', ' Firefox ESR ')}). Pipe ($.sourcemaps.write () )//. tmp temp directory, and later a directory is the Dist directory, just imagine, if we compile BootStrap and there is no reference in HTML, then it is necessary to compile it? So,. tmp as a temporary directory, it can hold the compiled files, but not necessarily be referenced. The file that is really referenced is the file that is really useful, and we put it in the Dist directory. So the next HTML processing is to check what CSS and JS are referenced, you can merge them, then put the new file into the Dist and update its reference path: pipe (Gulp.dest ('. Tmp/styles ')). Pipe (Reload ({stream:true});}); /compile Jsgulp.task (' Scripts ', () = {return gulp.src (' app/scripts/**/*.js '). Pipe ($.plumber ()). Pipe ($.sourcemaps.    Init ()). Pipe ($.babel ()). Pipe ($.sourcemaps.write ('. ')) . Pipe (Gulp.dest ('. tmp/scripts ')). Pipe (Reload ({stream:true}));}); function lint (files, options) {return gulp.src (Files). Pipe (Reload ({stream:true, once:true})). Pipe ($.eslint (opt ions). Pipe ($.eslint.format ()). Pipe ($.if (!browsersync.active, $.eslint.failaftererror ()));} Gulp.task (' Lint ', () = {return Lint (' App/scripts/**/*.js ', {fix:true}). Pipe (Gulp.desT (' app/scripts ');});    Gulp.task (' Lint:test ', () = {return Lint (' Test/spec/**/*.js ', {fix:true, env: {mocha:true}}) . Pipe (Gulp.dest (' test/spec/**/*.js ');}); /compile Htmlgulp.task (' html ', [' Styles ', ' Scripts '], () = {return gulp.src (' app/*.html ')//useref this plugin, which can detect references in HTML    CSS and JS, you can perform the merging and compression, and then update the new path: pipe ($.useref ({searchPath) (['. tmp ', ' app ', '. ')})    . Pipe ($.if (' *.js ', $.uglify ())). Pipe ($.if (' *.css ', $.cssnano ({safe:true, autoprefixer:false}))//options = { Removecomments:true,//Clear HTML comments//Collapsewhitespace:true,//compress HTML//collapsebooleanattributes:true,// Omit the value of the Boolean attribute <input checked= "true"/> ==> <input checked/>//removeemptyattributes:true,//delete all spaces as attribute values &lt Input id= ""/> ==> <input/>//removescripttypeattributes:true,//delete <script> type= "Text/javascrip T "//Removestylelinktypeattributes:true,//delete <style> <link> type=" text/css "//Minifyjs:true,  Compress page JS//minifycss:true//Compress page CSS//}; . Pipe ($.if (' *.html ', $.htmlmin ({collapsewhitespace:true})). Pipe (Gulp.dest (' dist '));}); Gulp.task (' images ', () = {return gulp.src (' app/images/**/* ')//compress only modified pictures, uncompressed read//optimizationlevel:5 from cache file,// Type: Number default: 3 Value range: 0-7 (Optimization level)//progressive:true,//Type: Boolean default: False lossless compression JPG image//interlaced:true,//type: Bool EAN default: False interlaced GIF rendering//multipass:true//Type: Boolean default: False optimize SVG multiple times until fully optimized//svgoplugins: [{Removeviewbox:fal se}],//do not remove the SVG viewbox attribute//use: [Pngquant ()]//imagemin plug-in that uses pngquant depth to compress PNG images. Pipe ($.cache ($.imagemin ({prog Ressive:true, Interlaced:true,//don ' t remove IDs from SVGs, they is often used//as hooks for Embeddi Ng and Styling Svgoplugins: [{cleanupids:false}]})). Pipe (Gulp.dest (' dist/images '));}); Gulp.task (' Fonts ', () = {return gulp.src (require (' main-bower-files ') (' **/*.{ EOT,SVG,TTF,WOFF,WOFF2} ', function (err) {}). concat (' APp/fonts/**/* '). Pipe (Gulp.dest ('. tmp/fonts ')). Pipe (Gulp.dest (' dist/fonts '));}); Gulp.task (' Extras ', () = {return Gulp.src ([' App/*.* ', '!app/*.html '], {dot:true}). Pipe (Gulp.dest (' di (ST '));}); Gulp.task (' Clean ', del.bind (null, ['. tmp ', ' Dist '])); Gulp.task (' Serve ', [' Styles ', ' scripts ', ' Fonts '], () = {brows Ersync ({notify:false, port:9000, server: {baseDir: ['. tmp ', ' app '], routes: {'/bower_compon  Ents ': ' bower_components '},//This is an agent cross-domain, the rule above has defined the middleware: [Proxy]}});  Gulp.watch ([' app/*.html ', ' app/images/**/* ', '. tmp/fonts/**/* ']). On (' Change ', reload);  Gulp.watch (' app/styles/**/*.scss ', [' Styles ']);  Gulp.watch (' app/scripts/**/*.js ', [' Scripts ']);  Gulp.watch (' app/fonts/**/* ', [' fonts ']); Gulp.watch (' Bower.json ', [' wiredep ', ' fonts ']);    Gulp.task (' Serve:dist ', () = {Browsersync ({notify:false, port:9000, server: {baseDir: [' Dist '] }  });}); Gulp.task (' Serve:test ',[' Scripts '], () = {Browsersync ({notify:false, port:9000, Ui:false, server: {baseDir: ' Test ',  Routes: {'/scripts ': '. tmp/scripts ', '/bower_components ': ' Bower_components '}}});  Gulp.watch (' app/scripts/**/*.js ', [' Scripts ']);  Gulp.watch (' Test/spec/**/*.js '). On (' Change ', reload); Gulp.watch (' test/spec/**/*.js ', [' lint:test ');}); /Inject Bower Componentsgulp.task (' WIREDEP ', () = {gulp.src (' app/styles/*.scss '). Pipe (WIREDEP ({Ignorepath  :/^ (\.\.\/) +/}). Pipe (Gulp.dest (' app/styles ')); GULP.SRC (' app/*.html '). Pipe (WIREDEP ({exclude: [' Bootstrap-sass '], Ignorepath:/^ (\.\.\/) *\.\./})). P Ipe (Gulp.dest (' app ');}); /execute the build before executing the task Gulp.task (' Build ', [' Lint ', ' html ', ' images ', ' fonts ', ' extras '], () = {return Gulp.src (' dist/ **/* '). Pipe ($.size ({title: ' Build ', gzip:true})); /gulp==gulp Default Execution Task Gulp.task (' Default ', [' Clean '], () = {Gulp.start (' Build ');});

  

Yeoman+bower+gulp Web front-end Automation workflow (beginner tutorial)

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.