Learning Grunt - Douglas Reynolds - E-Book

Learning Grunt E-Book

Douglas Reynolds

0,0
26,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Monitor and automate complex JavaScript tasks and processes by obtaining a practical understanding of Grunt

About This Book

  • Gain a solid knowledge of Grunt to achieve better process management by improving consistency, productivity, reliability, and quality of code
  • Install, configure, and use plugins into your project with this hands-on guide
  • This step-by-step tutorial will walk you through practical examples of workflow automation

Who This Book Is For

If you are a JavaScript developer and want to learn project monitoring and automation using Grunt, then this book is for you. Basic knowledge of Node.js and Angular.js is assumed. However, no previous experience using Grunt.js is required.

What You Will Learn

  • Install and configure Grunt and its dependencies such as Node.js and Node Package Manager (NPM)
  • Create a sample application using Angular.JS
  • Configure plugins to perform various tasks that will benefit your project
  • Explore the task-specific methods available through the Grunt API such as configuration, externals, events, and logging
  • Set up tasks to automate the build process of the simple contact application
  • Build, test, and refine a sample project
  • Get general tips, tricks, and troubleshooting strategies to identify and solve common issues in Grunt
  • Advance your knowledge of Grunt with concepts such as configuration variables and test automation

In Detail

With the increasing focus on task automation, the Grunt task runner is a vast platform that allows you to incorporate automation into your workflows.

At the outset, you will learn how to use Node.js and NMP through an example. You will then find out how to build a sample app and the development environment for it. You will further delve into the implementation of Grunt plugins and the configuration of Grunt tasks. Furthermore, you will explore the various methods and packages for workflow automation. The final chapter will cover some advanced concepts, such as configuration variables and how to create a Grunt plugin.

By the end of the book, you will have gained the fundamentals of Grunt and progressed through advanced concepts, including building a Grunt plugin.

Style and approach

This book is an easy-to-follow, step-by-step tutorial that provides explanations and examples of deploying Grunt from scratch.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 188

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Grunt
Credits
About the Author
Acknowledgement
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Grunt Dependencies
Dependencies
What is Node.js and NPM?
Where can I find Node.js and NPM?
Upgrading or installing Node.js
Upgrading Node.js via NPM on Mac
Upgrading Node.js on Windows via .msi and NPM
The pristine installation of Node.js via downloaded binary
Adding your installation path to your $PATH variable
Using NPM to install the Grunt Command Line Interface
Installing the Grunt CLI
Updating NPM
Installing Grunt CLI
Summary
2. Foundation for Creating an App using Angular.JS
Installing Git
Determining the Git installation
Creating a temporary alias
Adding Git to your $PATH variable
Installation of Git
Creating the Angular Seed Project
Dependencies of Angular Seed
Cloning the Angular Seed Project
Installing Angular Seed dependencies
Running the Angular Seed Application
Installation summary – a quick guide
Installing Git
Determining Git Installation
Create the Angular Seed Project
Summary
3. All about Grunt Plugins
Obtaining Grunt plugins
Plugins overview
Actually obtaining Grunt plugins
Common Grunt plugins and their purposes
Linting JavaScript – contrib-jshint
Minifying Javascript – contrib-uglify
Compile LESS into CSS – contrib-less
Desktop notifications for automated tasks – notify
Opening files and URLs automatically – open
Optimizing images – contrib-imagemin
Running tasks only on files that changed – newer
Performing SSH and SFTP tasks – ssh
The minification of CSS – contrib-cssmin
Concatenate files – contrib-concat
Cleaning up files and folders – contrib-clean
Minifying HTML files – contrib-htmlmin
Watch for changing files - contrib-watch
Summary
4. Configuration of Grunt Tasks
Reviewing the installation of Grunt tasks
Installing contrib-jshint with NPM
Installing contrib-uglify with NPM
Installing contrib-less with NPM
Installing contrib-watch with NPM
Discussing package.json and gruntfile.js
The package.json file
The gruntfile.js file
Introducing the Grunt API
The wrapper function and initConfig
Loading NPM tasks:
Creating tasks
Grunt fail API
The Grunt event API
The Grunt file API
The Grunt log API
The Grunt option API
Grunt Template API
The Grunt task API
Summary
5. Task Setup in the sample_project Application
Defining requirements of sample_project
An overview of user stories
The slide deck
Gruntfile.js wrapper and configuration
Wrapper
grunt-init-gruntfile
Gruntfile.js configuration
Summary
6. Building the Sample Project
Understanding task loading
Using the LoadNpmTasks method
Calling plugins using the loadNpmTasks method
Using the devDependencies object looping method
The default task configuration
A custom task configuration
Functional testing
Testing the contrib-jshint configuration
Testing the contrib-uglify configuration
Testing the contrib-less Configuration
Testing the contrib-imagemin configuration
Testing the notify configuration
Testing the open configuration
Testing the contrib-watch Configuration
The Complete Gruntfile.js
Summary
7. Advanced Grunt Concepts
Creating a Grunt plugin
Using the Grunt plugin scaffold
Authoring a custom plugin
Summary
Index

Learning Grunt

Learning Grunt

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: March 2016

Production reference: 1210316

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-880-9

www.packtpub.com

Credits

Author

Douglas Reynolds

Reviewer

Justin McCandless

Commissioning Editor

Amarabha Banerjee

Acquisition Editor

Sonali Vernekar

Content Development Editor

Riddhi Tuljapurkar

Technical Editor

Danish Shaikh

Copy Editor

Tasneem Fatehi

Project Coordinator

Sanchita Mandal

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Graphics

Disha Haria

Production Coordinator

Nilesh Mohite

Cover Work

Nilesh Mohite

About the Author

Douglas Reynolds is a web application developer. He holds a degree in software engineering and has worked with web technologies for over 15 years. Douglas currently works for Herff Jones as a Senior Web Applications Developer as a member of a highly skilled and dedicated team of professionals. Douglas writes and lectures on web technologies, teaches at Illinois State University in the Department of Technology, and writes on topics of technology for Packt Publishing. Douglas and his wife of over 20 years, along with their son and two dogs, live in Bloomington, Illinois. He loves his family and friends and enjoys spending time outdoors in nature, riding his Harley, and continually developing his relationship with God.

Acknowledgement

Thank you, Lord, for the blessings in my life and providing me with what I need. I would like to thank Packt Publishing for giving me this incredible opportunity to write my first complete book. Having a published work has been a goal that I have thought about for many years. Special thank you to Sonali, who approached me with this idea and helped me take my first steps to begin writing and sharing information to help others learn. I have worked with a group of amazing people that have provided support and guidance to me on this project. I would especially like to thank Riddhi and Usha for their valuable cooperation and support. Justin's attention to detail and brilliant ideas helped me to refine the content into what I truly believe will provide a valuable resource to learning Grunt as well as a reference to return to again and again. Additionally, my most heartfelt thanks go to my beloved family, my wife Patricia, my son Zachary, and our dogs Penny and Juno (they spent countless hours accompanying me at my desk).

 

Once you make a decision, the Universe conspires to make it happen

  --Ralph Waldo Emerson

About the Reviewer

Justin McCandless is a software engineer and a build-process nerd originally from Las Vegas. He has studied electrical engineering at the University of Michigan before spending several years working abroad in Latin America and China. He now resides in San Francisco and works as a full-time engineer at Teespring. He enjoys contributing to the programming community through the open source platform, technical writing, and mentorship.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

The essence of workflow automation is an exemplification of at least two of the three great virtues of a programmer.

 

There are three great virtues of a programmer: laziness, impatience, and hubris.

  --–LarryWall, Programming Perl (1st edition), Oreilly And Associates

Larry Wall went on to explain that laziness is the quality that makes you go to great effort to reduce overall energy expenditure. Grunt provides task automation to relieve the developer of the mundane, repetitive processes that occur during software development. Expending effort up front with Grunt will pay dividends in reduction of energy expenditure in the development lifecycle. Impatience, Larry Wall said, makes you write programs that don't just react to your needs but actually anticipate them. Grunt automation can react to your needs by responding to events, such as file changing. With the right combination of tasks and configurations, Grunt automation can even seem as if it is anticipating your next step. Learning Grunt aims to provide you with a ramp from getting up and running to developing your own Grunt plugin. If you are at all lazy and impatient, in the context of a virtuous programmer, then Learning Grunt has been written just for you.

What this book covers

Chapter 1, Grunt Dependencies,will let us know that Grunt is a Javascript task runner, the purpose of which purpose is task automation. Before we can get started with Grunt, we need to make sure we understand and implement Grunt's prerequisites.

Chapter 2, Foundation for Creating an App using Angular.JS, will create a sample application to use throughout this book with the Angular-Seed scaffold.

Chapter 3, All about Grunt Plugins, introduces a sampling of common Grunt plugins, overview of their purposes, brief examples of implementation, and additional references and information.

Chapter 4, Configuration of Grunt Tasks, As we became familiar with installation and configuration of Grunt tasks. Focus is placed on two main files in a Grunt project; package.json and Gruntfile.js.

Chapter 5, Task Setup in the sample_project Application, defines the sample_project automated build process, introduces user stories, and then covers Gruntfile.js configuration from top to bottom.

Chapter 6, Building the Sample Project, will explain the process of loading tasks. We check functionality to ensure we get the expected results, and create custom and default tasks in order to automate the build process.

Chapter 7, Advanced Grunt Concept, will help you create your own custom task. Learn how to use the Grunt plugin tool and then write a custom Javascript plugin to Gzip files into a deployment directory

What you need for this book

Any modern Windows, Linux, or Macintosh computer, a text editor, command-line or terminal interface, and an Internet connection will meet the requirements of this book. Node.js is very lightweight and requires a minimal amount of RAM. The sample project will require approximately 500 MB of storage, although 1 GB of storage is recommended.

Who this book is for

If you are a JavaScript developer and want to learn project monitoring and automation using Grunt, then this book is for you. Basic knowledge of Node.js and Angular.js is assumed. However, no previous experience using Grunt.js is required.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can include other contexts through the use of the include directive.

A block of code is set as follows:

[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Grunt Dependencies

Grunt is a JavaScript task runner. As its name alludes, this tool performs the grunt work of completing development tasks, which might include linting JavaScript, running tests, generating minified JavaScript and CSS, moving files and directories, creating archives, and the list goes on and on. In fact, the purpose of Grunt is task automation, which means running one or more tasks with the least amount of user interaction needed in order to complete the work. Almost any task can be automated with Grunt and many plugins (tasks) already exist that can be installed and used in your project. It is possible to write and publish your own plugins to meet the need of tasks for which a plugin does not already exist. You can also modify existing plugins to meet project-specific requirements. The Grunt community is very large and there is a great deal of documentation and resources available as a result. With a minimum amount of research effort, information on specific Grunt topics can be found in a wide range of places. This book, for one, will provide information on the installation and setup of Grunt, installation and configuration of tasks found in the Node Package Manager (NPM) registry, creation of custom tasks, Grunt API documentation, and much more. Some main benefits of using the Grunt task runner are that Grunt task automation improves productivity by handling repetitive tasks with efficiency, reduces errors using automated processes, and lessens the workload so that less time and energy is spent on things that can be handled through workflow automation. Once the upfront work of Grunt implementation has been completed, there is practically no additional work needed to run tasks. It is a very simple matter to create custom task runners for various build stages of projects with fine-grained control over what tasks get run for various stages. For instance, it is possible to create a custom task that includes error checking and syntax validation, running a suite of unit tests, and then, upon success, building the project to a development release version and generating a deployment archive. The possibilities for various build configurations are vast. However, first things first, there are some things that need to be discussed prior to diving in.

Dependencies

Before jumping into Grunt.js, you first need to understand that Grunt has some dependencies that are needed in order to get up and running with task automation. In this case, the dependencies are Node.js and Node Package Manager (NPM). While a deep level of Node.js knowledge is not a prerequisite to using Grunt.js, a high-level understanding of Node.js and NPM is needed to get started.

Node.js and NPM are required for the installation of the Grunt command line interface (CLI) as well as plugins that are used for task automation in Grunt. We will get into plugins later in the book, so don't be too concerned with what exactly a plugin is at this point. Suffice it to say that a plugin is a script that performs a certain task in Grunt. These tasks can be run individually or as a series of tasks that run as part of what is called a custom task. Some examples of common tasks are as follows:

JSHint: JSHint runs JavaScript validation (lint). This runs code that analyzes JavaScript for errors or syntax that has the potential to be a bug.Uglify: This task minifies files by removing all excess characters from code without changing or breaking the functionality of the code.LESS: This is a task that compiles LESS files into CSS files.Watch: This responds to additions, changes, and deletions of files by running preconfigured tasks, for instance, if you wish to build your project or run lint on files every time the file is changed and saved.

An example usage scenario, using these tasks listed, might be to run JSHint to lint JavaScript source files. If errors exist, the task halts and provides message(s) related to the errors and warnings found. If no errors exist, then the task completes and the Uglify task is run to minify the JavaScript source files, outputting them to the distribution directory. Next, the LESS task is run to generate and output CSS to the distribution directory. Finally, the Watch task is run so that it will continue to monitor changes to files when they occur. Watch might start the entire build process again without any user interaction. This is really powerful and frees up the developer who would otherwise need to perform each task manually every time files were changed.

There are many official plugins such as these that have been created and are maintained by the Grunt team. Official plugins are prefixed with contrib-, so the naming of plugins listed previously would be found as contrib-jshint, contrib-uglify, contrib-less, and contrib-watch as each one of these plugins is officially maintained by the Grunt team.

There are unofficial plugins created and contributed to the project by other organizations and developers as well. Examples of common unofficial plugins include the following:

concurrent: This runs tasks concurrentlynewer: This runs tasks on source files that have changedopen: This opens URLs and files from a tasknotify: This provides automatic desktop notifications for errors and warnings

What has been listed here isn't even the tip of the iceberg of the plugins available to add to your project for workflow automation. You might find that you are spending time on a task that is repetitive and error prone. What if you could write a script that would perform this task for you and ensure that it is done correctly every time? Well, with Grunt, you can create your own plugins and even contribute them to the NPM registry so that others who have the same need can benefit.

Now that we have a bit of introduction of what Grunt can do, let's discuss more about the Node.js and NPM dependencies. In the following sections, we will get to know some introductory information about Node.js and NPM. We will look at procedures for the installation of Node, which will include upgrade processes as well as pristine installations on both Mac and Windows. The Grunt Command Line Interface will be introduced; this is where we will actually begin working with Grunt tooling:

An overview of Node.js and NPMUpgrading or installing Node.jsUsing NPM to manage the Grunt CLI

Grunt.js and Grunt plugins require Node.js and NPM in order to be installed. As a result, Node.js and NPM are dependencies of Grunt. Node.js is the server environment in which Grunt will run. NPM is the package manager that will be used to install plugins from the NPM repository. NPM will make it easy to install code written by other developers who have shared their solutions so that others, such as us, can benefit from reuse.

In order to go further into details about Node.js and NPM, the following questions will be answered in this section:

What is Node.js and NPM?Where can I find Node.js and NPM?

What is Node.js and NPM?

Node.js is a runtime environment that uses the Google V8