"Go" yeoman:web application development process and tools

Source: Internet
Author: User
Tags html5 boilerplate

Translated from: http://blog.jobbole.com/62098/

With the popularity of Web 2.0 and HTML 5, today's Web applications are much more powerful and interactive than traditional Web applications. Many of the implementation logic of the application is transferred to the browser side to implement. Instead of providing a single data reception and presentation capability, the browser provides more user interaction capabilities. The HTML, CSS, and JavaScript code included in the browser also become more complex. For increasingly complex front-end code, there is a need for better processes and tools to manage all aspects of development, including the initial code structure, the development process, and automated testing. Yeoman is an emerging tool. It combines tools such as Yo, Grunt and Bower to form a complete set of tools that provide the practical features you need to develop a variety of WEB applications.

The biggest advantage of Yeoman is that it integrates a variety of popular utilities and provides a one-stop solution that makes many aspects of WEB application development easier. Yeoman allows developers to focus on the implementation of the application itself, rather than spending too much time and effort on building an application's infrastructure, doing task building, and other ancillary tasks. Yeoman also automatically introduces some good best practices into the development of the project. For example, when you need to use a third-party JavaScript library in your app, it's common practice to download it directly to the library's Web site. In Yeoman, it is a better practice to rely on Bower for management.

The functionality of Yeoman is implemented by the tools it contains. The following are the tools for Yo, Grunt, and Bower included in Yeoman.

Grunt

Grunt is a JavaScript task execution tool whose core philosophy is automation. There are many different tasks that need to be performed during WEB application development. These tasks are related to the different types of components in Web app development and the stages in which they are located. For JavaScript, for example, in the development phase you will need tools such as JSLint and jshint to check the quality of JavaScript code, and in the build phase, from the perspective of front-end performance, you will need to compress multiple JavaScript files after merging. There are similar tasks for CSS files that need to be performed. Other tasks include compressing pictures, merging compression and confusing JavaScript code, and running automated unit test cases. All of these tasks need to be configured and run in a corresponding way. Different tasks run differently, depending on the technology used by the task itself. For example, some JavaScript-related tasks, such as JSLint and Jshint, run through the JavaScript engine. For generic Java platform-based WEB applications, if you need to perform jslint tasks, you need to use an engine like Rhino to execute JavaScript code while integrating with build tools such as Apache Ant, Maven, or Gradle. The problem with this approach is that different tasks are configured differently and need to be integrated with existing build systems. Developers need to query a lot of documents to know how to configure and use these tasks.

Grunt is based on the popular NodeJS platform to run. All task execution is based on a unified platform. The advantage of Grunt is that it integrates very many task plugins. Some of these plugins are developed by the Grunt team, and more are contributed by the community. These plugins are distributed using the NodeJS standard module mechanism and can be managed using NPM only. The Web app only needs to pass a file to declare the tasks to be performed and configure them accordingly, and Grunt will be responsible for running the tasks. In this way, the configuration of all tasks is managed in one file.

The Grunt installation process is simple. You only need to run the NPM install-g grunt-cli command to install it. When the Yeoman is installed, Grunt is automatically installed as part of the installation. For an app, two files are required to use Grunt. One is the Package.json used by NPM. The file contains the relevant metadata for the app. In this file, you need to declare a dependency on Grunt and other plugins through devdependencies. Another file is Gruntfile, which can be a JavaScript or Coffeescript file. The purpose of this file is to configure the tasks that need to be performed in your app. After you have declared dependencies in the Package.json file and installed the Grunt plug-in, you can configure and load these tasks in Gruntfile. You can run these tasks by using the grunt command. Different tasks are configured in a relatively similar way, except that the configuration items provided are not the same.

Task configuration

The related configuration in Gruntfile is included in a JavaScript method. In this method, the plug-in used can be configured with the Grunt.initconfig method. Because some of the values in the Package.json file are often required for configuration in the Gruntfile file, it is common practice to read the contents of Package.json into a property for easy use in other parts of the code. Code Listing 1 shows the basic structure of the gruntfile. The Pkg property in the Parameter object that calls the Initconfig method represents the contents of the Package.json.

Listing 1. The basic structure of gruntfile
12345 module.exports = function(grunt) {  grunt.initConfig({    pkg: grunt.file.readJSON(‘package.json‘)  });};

You can include any property value in the Configuration object. It is important, however, that the configuration items for the plug-ins that perform the different tasks are. The property name of each plug-in configuration item in the configuration object corresponds to the name of the plug-in. For example, the Grunt-contrib-concat plug-in corresponds to the configuration Item property name Concat, as shown in Listing 2. The role of plug-in Grunt-contrib-concat is to stitch together multiple JavaScript files to form a single file. In the configuration item for the plug-in, the SRC and dest attributes represent the JavaScript file to be spliced and the name of the generated target file, respectively. Where the value of the SRC attribute is specified with a wildcard character for a series of files, the value of the property name defined in the Package.json file is referenced by Pkg.name in the values of the Dest property. "<%=%>" is the syntax format of the string template provided by Grunt, which is used to generate a string based on the value of the variable.

Listing 2. Configuration of the plugin Grunt-contrib-concat
1234 concat: {  src: [‘src/**/*.js‘],  dest: ‘dist/<%= pkg.name %>.js‘}

The Grunt template uses "<%%>" to separate expressions, and also supports nesting of expressions. When you parse content contained in a template, the entire configuration object is used as the context for parsing. This means that the properties contained in the configuration object can be referenced directly in the template. In addition, grunt objects and the methods they contain can also be used in templates. There are two forms of the template: The first is "<%=%>", which refers to the property values in the Configuration object, and the second is "<%%>", which is used to execute arbitrary JavaScript code, usually to control the code execution process.

Some plugins allow you to define multiple different configurations at the same time, called different "targets." This is because some tasks do not have the same configuration under different conditions. For these different goals, you can add a property of the corresponding name to the configuration object to represent it. Code Listing 3 shows another way to configure the Grunt-contrib-concat plugin. Common and all two different targets are defined in the code. The configuration of each target is not the same. When you run a task, you run different targets through "grunt Concat:common" and "Grunt Concat:all". If you do not specify a specific target, but instead use "Grunt concat" to run directly, all targets are executed in turn.

Listing 3. Multi-target configuration for plug-in Grunt-contrib-concat
12345678910 concat: {  common: {    src: [‘src/common/*.js‘],    dest: ‘dist/common.js‘  },  all: {    src: [‘src/**/*.js‘],    dest: ‘dist/all.js‘  }}

For configurations that contain multiple targets, you can configure the default attribute values for different targets by using the Options property. The Options property can also be used to override default values in the target.

Task creation and execution

After you configure the plug-in, you need to create related tasks in Gruntfile. These tasks are performed by Grunt. After the Grunt plugin is loaded, the plug-in provides tasks that can be executed. You can also use the Grunt.registertask method to define a new task or create an alias for an existing task. When you define a task, you provide the name of the task and the method that is executed. The description of the task is optional. A simple task is given in code Listing 4. When you run the task through grunt sample, the appropriate prompt is output in the console.

Listing 4. A simple Grunt task
123 grunt.registerTask(‘sample‘, ‘My sample task‘, function() {  grunt.log.writeln(‘This is a sample task.‘);});

When you define a task, you can declare the parameters that are required for the task to run, and you can specify values for those parameters when you run the task through grunt. Code Listing 5 shows an example of a task that contains parameters. The task profile needs to provide 2 parameters at runtime name and email. When running through grunt, use "grunt Profile:alex:[email protected" to pass the parameter value "Alex" and "[email protected]" respectively to the parameter name and email. Different parameters are separated by ":".

Listing 5. Grunt tasks that contain parameters
123 grunt.registerTask(‘profile‘, ‘Print user profile‘, function(name, email) {  grunt.log.writeln(‘Name -> ‘ + name + ‘; Email -> ‘ + email);});

If the task you are defining is similar to GRUNT-CONTRIB-CONCAT plug-ins that can support multiple different targets, you only need to use the Grunt.registermultitask method to define them.

In addition to defining new tasks, you can create new tasks by adding aliases to existing tasks. The Code Listing 6 shows an example. Tasks named default execute tasks such as Jshint, Qunit, concat, and uglify, in turn. When you run the grunt command, if you do not specify a task name, you try to run a task named default.

Listing 6. Tasks created using the Add Alias method
1 grunt.registerTask(‘default‘, [‘jshint‘, ‘qunit‘, ‘concat‘, ‘uglify‘]);

Most of the tasks are performed synchronously, or they can be executed asynchronously. If a part of the task takes a long time to complete, it can be done asynchronously. Code Listing 7 shows an example of a task that executes asynchronously. You can make the execution of the current task asynchronous by calling the Async method. Calling the return value of the Async method is a JavaScript method. When the task executes, call the JavaScript method to notify Grunt.

Listing 7. Tasks that are performed asynchronously
1234567 grunt.registertask (' Asynctask ', function () {     var done = This.async (); &NBSP;&NBSP; settimeout (function () {      grunt.log.writeln (' done! '); &NBSP;&NBSP;&NBSP;&NBSP; done (); &NBSP;&NBSP; }, +);

A task can depend on the successful execution of other tasks. When a task fails to execute, the remaining tasks are not executed unless the "–force" parameter is used when the grunt command is executed. You can declare dependencies on other tasks in the task code by using the Grunt.task.requires method. If the dependent task does not execute successfully, the current task is not executed. When the task's corresponding JavaScript method returns false at execution time, the task is considered to have failed to execute. For a task that executes asynchronously, you only need to pass in the false parameter when calling the callback method returned by async. For example, in code listing 7, you can use "done" (false); To declare that the asynchronous task failed to execute.

To be able to use the tasks provided by the plug-in when calling Grunt, you need to use the Grunt.loadnpmtasks method to load the plug-in. Code Listing 8 shows an example of loading the Grunt-contrib-watch and Grunt-contrib-concat plugins.

Listing 8. Plug-in loading example
12 grunt.loadNpmTasks(‘grunt-contrib-watch‘);grunt.loadNpmTasks(‘grunt-contrib-concat‘);
Bower

In Web app development, there are a number of third-party JavaScript libraries, such as JQuery and Twitter Bootstrap, that are commonly used. It's a traditional practice to download the required version of the JavaScript library file directly from the library's web site, put it in a directory in your Web app, and then reference it in an HTML page. The problem with this approach is that it introduces a lot of extra work, including finding the required JavaScript library files, downloading and managing them, and so on. Some JavaScript libraries are available in a number of versions, and also rely on other JavaScript libraries. For a given version of a JavaScript library, you need to find other JavaScript libraries on the compatible version on which it depends. This can be a recursive process that can take a lot of time. Bower is a front-end library management tool that resolves issues you might encounter when referencing third-party libraries in a WEB application. Bower provides features similar to the Apache Ivy, Apache Maven, or Gradle tools that will be used in Java development.

Bower is also based on the development of NodeJS. You only need to use the NPM install-g Bower command to install. The Yeoman also contains the Bower when installed. After Bower is installed, you can use the Bower command at the command line to manage the required libraries. You can view the actions supported by the Bower command line through Bower Help. It is a common practice to search for libraries that need to be used first through the "Bower Search" command. For example, "Bower search jquery" can be used to search for a library with jquery in its name. After you find the library you want, you can install it by using the Bower Install command. such as "Bower install Jquery-ui" can be used to install the jquery UI Library. You can specify a version of the library at installation, such as "Bower Install jquery-ui#1.9.2" to install the 1.9.2 version of the jquery UI. When you use the name to install the library, you are asked to register the library with Bower. Bower also supports the installation of libraries from remote or local Git repositories and local files. Bower will place the downloaded library file in the Bower_components directory. When the library is updated, it is updated with the "Bower Update" command. When a library is not needed, it is removed by the "Bower Uninstall" command. Use the Bower List command to list information about the libraries that are already installed in the current app.

After installing the library through Bower, you can refer directly to the HTML page, as shown in Listing 9. This requires that the Bower download directory be publicly accessible.

Listing 9. Introduction of Bower-managed JavaScript libraries in HTML pages
1 <script src="/bower_components/jquery/jquery.min.js"></script>

A better way to do this is to define the libraries you rely on in the Bower.json file, and then run the "Bower Install" command to install all of the libraries, compared to the libraries you need to install one after the other. The Bower.json file acts like a Package.json in NodeJS. You can create the file directly, or you can create it interactively by using the Bower init command. Code Listing 10 shows an example of the Bower.json file. Use dependencies to declare the libraries that you depend on and their versions. With the Bower.json file, you only need to run the "Bower Install" command once to install all the libraries you need.

Listing 10. Bower.json File Example
1234567891011 {  "name": "yeoman-sample",  "version": "0.1.0",  "dependencies": {    "sass-bootstrap": "~3.0.0",    "requirejs": "~2.1.8",    "modernizr": "~2.6.2",    "jquery": "~1.10.2"  },  "devDependencies": {}}

The configuration of the Bower itself can be done through the. bowerrc file. The file is configured in JSON format. Code Listing 11 shows an example of a. bowerrc file. The directory for the Bower download library is defined in this example through directory.

Listing 11. Configuring the. bowerrc file for Bower
123 {    "directory": "app/bower_components"}
Yo

When you plan to start developing a WEB application, the initial directory structure and underlying files are important because they are the basis for application development. Some developers choose to start from scratch or copy existing apps. A better choice is based on the existing template. Many WEB applications use templates such as HTML5 boilerplate to generate the initial code structure. The advantage of this is that you can directly reuse existing best practices, avoid many potential problems, and lay a good foundation for future development. Yo is a WEB application Architecture (Scaffolding) tool. It provides a very wide range of templates to generate different types of WEB applications. These templates are called generators (generator). The community has also contributed a lot of generators, adapting to a variety of different scenarios. Use Grunt to build using the Yo-generated app and use Bower for dependency management.

As an example of a basic Web Application builder, you only need to use the "Yo webapp" command to generate a skeleton for a basic Web application. After you run the command, there are some hints to configure the generated app in a basic configuration, and you can select the features you want to include. The default generated Web app includes HTML5 boilerplate, jQuery, MODERNIZR, and Twitter Bootstrap. With just one simple command, you can build a Web app that runs directly. Subsequent development can be based on the resulting application skeleton. This simplifies the development of the application to a great extent, especially in some prototyping applications.

Some of the common Grunt tasks are included in the generated Web app. These tasks can help you develop quickly. These tasks include:

    • Grunt server: Start the servers that support Live Reload technology. When a local file is modified, the page that is opened automatically refreshes to reflect the latest changes. This eliminates the hassle of each manual refresh, making the development process easier and faster.
    • Grunt test: Run Mocha-based automated tests.
    • Grunt Build: Build your entire Web app. The tasks performed include merging, compressing, and confusing JavaScript and CSS files, adding version numbers, and so on.
Yeoman

The important point of Yeoman is to integrate various tools to form a complete front-end development workflow. The development process after using Yeoman can be divided into the following basic steps.

At the initial stage of development, the front-end technology selection needs to be determined. This includes selecting the front-end frame to use. In most WEB application development, third-party library support is required. Some apps may use jQuery only, and some apps will add Twitter Bootstrap libraries, while others will use AngularJS. After you have identified the technology selection, you can find the appropriate generator plug-in in the Yeoman. In general, generators based on common libraries can be found in the community. For example, use the AngularJS, Backbone, Ember, and Knockout framework generators.

All generators are installed using NPM. The name of the generator is prefixed with "generator-", such as "Generator-angular", "Generator-backbone", "Generator-ember", and so on. Once the installation is complete, the app's skeleton code can be generated with the Yo command, such as "Yo angular" to generate an application skeleton based on AngularJS.

The resulting application skeleton contains a basic application that can be run. You only need to start the server with the "Grunt Server" command to view it. After the application skeleton is built, save the generated code to the source code repository. The team can develop on this basis. Some common tasks in development can be simplified by Yeoman. When a third-party library needs to be introduced, it is searched and added via Bower.

Summary

With the development of complex WEB applications, good process and tooling support is essential to make everyday development work smoother. As a popular toolset, Yeoman defines a more complete and clear workflow based on the integration of tools such as Yo, Grunt and Bower. By introducing some of the best practices into your WEB application, you can help create high-quality and maintainable applications.

"Go" yeoman:web application development process and tools

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.