Modern JavaScript Web Development Cookbook - Federico Kereki - E-Book

Modern JavaScript Web Development Cookbook E-Book

Federico Kereki

0,0
34,79 €

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

Mehr erfahren.
Beschreibung

JavaScript has evolved into a language that you can use on any platform. Modern JavaScript Web Development Cookbook is a perfect blend of solutions for traditional JavaScript development and modern areas that developers have lately been exploring with JavaScript. This comprehensive guide teaches you how to work with JavaScript on servers, browsers, mobile phones and desktops.
You will start by exploring the new features of ES8. You will then move on to learning the use of ES8 on servers (with Node.js), with the objective of producing services and microservices and dealing with authentication and CORS. Once you get accustomed to ES8, you will learn to apply it to browsers using frameworks, such as React and Redux, which interact through Ajax with services. You will then understand the use of a modern framework to develop the UI. In addition to this, development for mobile devices with React Native will walk you through the benefits of creating native apps, both for Android and iOS.
Finally, you’ll be able to apply your new-found knowledge of server-side and client-side tools to develop applications with Electron.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 611

Veröffentlichungsjahr: 2018

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.



Modern JavaScript Web Development Cookbook
Easy solutions to common and everyday JavaScript development problems
Federico Kereki
BIRMINGHAM - MUMBAI

Modern JavaScript Web Development Cookbook

Copyright © 2018 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 author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

Commissioning Editor: Kunal ChaudhariAcquisition Editor:Larissa PintoContent Development Editor: Flavian Vaz, Onkar WaniTechnical Editor:Rutuja VazeCopy Editor: Safis EditingProject Coordinator:Kinjal BariProofreader: Safis EditingIndexer:Rekha NairGraphics: Alishon MendonsaProduction Coordinator:Deepika Naik

First published: December 2018

Production reference: 1211218

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78899-274-9

www.packtpub.com

This book is more than deservedly dedicated, with my continued love, to Sylvia Tosar.
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

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.

Contributors

About the author

Federico Kereki is a Uruguayan systems engineer, with a master's degree in education, and over 30 years' experience as a consultant, system developer, university professor, and writer. He is currently a subject matter expert at Globant, and he has taught CS courses at Universidad de la República, Universidad ORT Uruguay, and Universidad de la Empresa.

He has written for the Linux Journal and the LinuxPro Magazine in the USA, Linux+ and Mundo Linux in Europe, and websites such as Linux.com and IBM DeveloperWorks. He has also written booklets on computer security, and two books—Essential GWT, and Mastering JavaScript Functional Programming.

This book couldn't have been possible without the continued support from my wife, Sylvia Tosar, who provided everything so I could work on this book—which was started while in a stint working in Pune, India, 10,000 miles away from home; continued for a short while in London, England; and only finished back home in Montevideo, Uruguay, but always with her by my side, in person or thanks to the internet.

About the reviewers

Bruno Joseph Dmello is currently working at Truckx as a web development consultant. He has six years' experience in web application development serving a variety of domains, including entertainment, social media, enterprise, and IT services. He is a JavaScript enthusiast, with four years' experience of working with it. Bruno follows Kaizen and enjoys the freedom of architecting new things on the web. He has also contributed to the community by authoring books such as Web Development in Node.js and MongoDB (version2, version 3), What You Need To Know About Node.js (free ebook), and JSON Essentials (version 2), and by being a reviewer.

Sasan Seydnejad has more than a decade of experience in developing web user interfaces and frontend applications using JavaScript, CSS, and frameworks such as Angular and React.

He specializes in modular SPA design and implementation, responsive mobile-friendly user interfaces, client application architecture, and UX design. He has worked and consulted for various tech companies, including Nokia and Trading Central. He is also the author of the book Modular Programming with JavaScript, by Packt Publishing.

Xun (Brian) Wuis the founder and CEO of smartchart.tech. He has 17+ years of extensive, hands-on experience on design and development with blockchain, big data, Cloud, UI, and system infrastructure. He has co-authored a number of books, including Seven NoSQL Databases in a Week, Hyperledger Cookbook, and Blockchain Quick Start Guide. He has been a technical reviewer on more than 40 books for Packt. He serves as a board adviser for several blockchain start-ups and owns several patents on blockchain. Brian also holds an NJIT computer science master's degree. He lives in New Jersey with his two beautiful daughters, Bridget and Charlotte.

I would like to thank my parents, wife, and kids for their patience and support throughout this endeavor.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Modern JavaScript Web Development Cookbook

Dedication

www.PacktPub.com

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Sections

Getting ready

How to do it...

How it works...

There's more...

There's more...

See also

Get in touch

Reviews

Working with JavaScript Development Tools

Introduction

Installing Visual Studio Code for development

How to do it...

How it works...

Extending Visual Studio Code

How to do it...

Adding Fira Code font for better editing

How to do it...

How it works...

Adding npm for package management

How to do it...

How it works...

Creating a project with npm

Installing packages for different purposes

There's more...

Doing version control with Git

How to do it...

There's more...

Formatting your source code with Prettier

How to do it...

How it works...

Documenting your code with JSDoc

How to do it...

How it works...

Adding code quality checks with ESLint

How to do it...

How it works...

There's more...

Adding Flow for data types checks

How to do it...

How it works...

Configuring Flow's linting

Using Flow within VSC

Using Modern JavaScript Features

Introduction

Adding types

Getting started

How to do it...

Basic types in Flow

Union types

Class types

Type aliases

Generic types

Opaque types for safer coding

Working with libraries

Working with strings

How to do it...

Interpolating in template strings

Tagged templates

Writing multiline strings

Repeating strings

Padding strings

Searching in strings

Trimming strings

Iterating over strings

Enhancing your code

How to do it...

Working in strict mode

Scoping variables

Spreading and joining values

Destructuring arrays and objects

Doing powers

Defining functions

How to do it...

Writing arrow functions

Returning values

Handling this in arrow functions

Defining types for arrow functions

Defining default argument values

Programming functionally

How to do it...

Reducing arrays to values

Mapping arrays

Filtering arrays

Producing functions from functions

Doing async calls compactly

Getting started

How to do it...

Doing Ajax calls with promises

Doing Ajax calls with async/await

Working with objects and classes

How to do it...

Defining classes

Extending classes

Implementing interfaces

Static methods

Using getters and setters

Organizing code in modules

How to do it...

Doing modules the IIFE way

Redoing our IIFE module in the modern way

Adding initialization checks

Using more import/export possibilities

Using Flow types with modules

Determining a feature's availability

How to do it...

Developing with Node

Introduction

Checking Node's setup

How to do it...

How it works...

Working with modules

How to do it...

How it works...

Using Flow with Node, directly

How to do it...

How it works...

Using Flow with Node through preprocessing

How to do it...

How it works...

Running your Node code with Nodemon

How to do it...

How it works...

Using promises instead of error first callbacks

How to do it...

How it works...

There's more...

Working with streams to process requests

How to do it...

How it works...

Compressing files with streams

How to do it...

How it works...

Working with a database

Getting ready

How to do it...

Getting a connection

Executing some queries

Updating the database

Getting everything together

How it works...

There's more...

Executing external processes with exec()

How to do it...

How it works...

There's more...

Using spawn() to run a command, and communicating with it

How to do it...

How it works...

Using fork() to run Node commands

How to do it...

How it works...

Implementing RESTful Services with Node

Introduction

Developing a server with Express

How to do it...

How it works...

Adding middleware

Getting ready

How to do it...

How it works...

Getting request parameters

How to do it...

How it works...

Serving static files

How to do it...

How it works...

There's more...

Adding routes

How to do it...

How it works...

Implementing secure connections

How to do it...

How it works...

Adding security safeguards with Helmet

How to do it...

How it works...

Implementing CORS

How to do it...

How it works...

Adding authentication with JWT

How to do it...

How it works...

Tying it all together – building a REST server

How to do it...

How it works...

Handling GETs

Handling DELETEs

Handling PUTs

Handling POSTs

There's more...

Accepting JSON data

Adding the PATCH method for partial updates

Using Restify instead of Express

Allowing filtering, sorting, and pagination

Using GraphQL instead of REST

Implementing a microservice-based architecture

Testing and Debugging Your Server

Introduction

Adding logging with Winston

How to do it...

How it works...

There's more...

Adding HTTP logging with Morgan

How to do it...

How it works...

There's more...

Configuring your server for different environments

How to do it...

How it works...

There's more...

Unit testing your code

How to do it...

Doing functional tests

Using spies

Working with mocks

How it works...

There's more....

Measuring your test coverage

How to do it...

How it works...

Debugging your code

How to do it...

How it works...

Testing simple services from the command line

Getting ready

How to do it...

Testing more complex sequences of calls with Postman

Getting ready

How to do it...

Doing basic requests

Adding some checks

Chaining requests

How it works...

There's more...

Documenting and testing your REST API with Swagger

How to do it...

Writing our specs

Enabling Swagger

How it works...

Developing with React

Introduction

Starting out with React

How to do it...

How it works...

There's more...

Reinstalling your tools

How to do it...

Reinstalling Flow and Prettier

Reinstalling ESLint

How it works...

Defining components

How to do it...

Creating the application

Creating the basic App component

Creating the RegionsInformationTable component

Creating the CountryFilterBar component

Creating the ResultsDataTable component

Creating the ExpandableCard component

How it works...

There's more...

Handling state

How to do it...

How it works...

There's more...

Composing components

How to do it...

How it works...

Handling life cycle events

How to do it...

How it works...

Simplifying component development with Storybook

How to do it...

How it works...

There's more...

Enhancing Your Application

Introduction

Adding SASS for separate styling

How to do it...

How it works...

Creating StyledComponents for inline styling

How to do it...

How it works...

Making your application responsive to screen sizes

How to do it...

How it works...

Resizing elements

Reordering elements

Hiding or showing elements

Making your application adaptive for enhanced usability

How to do it...

How it works...

Making a global application with internationalization and localization

How to do it...

How it works...

Setting up for accessibility (a11y)

How to do it...

How it works...

Solving static problems

Solving runtime problems

There is more

Expanding Your Application

Introduction

Managing state with Redux

Getting ready

How to do it...

Defining actions

Writing a reducer

Defining the store

Building our components

Connecting components to the store

Defining the main page

How it works...

See also

Doing async actions with redux-thunk

How to do it...

Defining the actions

Writing the reducer

Modifying the country drop-down list

Modifying the region table

Setting up the main application

Using thunks

How it works...

There's more...

Adding routing with react-router

Getting started

How to do it...

How it works...

There's more...

Adding authorization to routes

How to do it...

Creating a login component

Defining actions and the reducer

Creating a component to protect a route

How it works...

There's more...

Code splitting for performance

Getting ready

How to do it...

How it works...

There's more...

Debugging Your Application

Introduction

Logging with style

Getting ready

How to do it...

How it works...

Debugging with the React Developer Tools

Getting Ready

How to do it...

How it works...

Debugging with the standalone tool

Getting ready

How to do it...

How it works...

Logging Redux with redux-logger

Getting ready

How to do it...

Setting up our counter application

Setting up our region application

How it works...

Logging the counter application

Logging the region application

Debugging Redux with the Redux Developer Tools

Getting ready

How to do it...

How it works...

Connecting routing for debugging

Getting ready

How to do it...

How it works...

Testing Your Application

Introduction

Testing components with Jest and Enzyme

Getting ready

How to do it...

Testing a component without events

Testing a component with events

How it works...

Testing reducers and mappings

How to do it...

How it works...

Testing actions and thunks

Getting ready

How to do it...

How it works...

Testing changes with Snapshots

How to do it...

How it works...

Running the tests

The produced snapshot files

Regenerating snapshots

Measuring test coverage

How to do it...

How it works...

Creating Mobile Apps with React Native

Introduction

Setting things up

How to do it...

How it works...

There's more...

Adding development tools

How to do it...

Adding ESLint

Adding Flow

Adding Prettier

How it works...

Using native components

Getting ready

How to do it...

How it works...

There's more...

Adapting to devices and orientation

How to do it...

How it works...

There's more...

Styling and laying out your components

How to do it...

How it works...

Adding platform-specific code

How to do it...

How it works...

There's more...

Routing and navigating

How to do it...

How it works...

There's more...

Testing and Debugging Your Mobile App

Introduction

Writing unit tests with Jest

Getting ready

How to do it...

How it works...

Adding snapshot testing

How to do it...

How it works...

Measuring test coverage

How to do it...

How it works...

Using Storybook to preview components

Getting ready

How to do it...

How it works...

Debugging your app with react-native-debugger

Getting started

How to do it...

How it works...

Debugging in an alternate way with Reactotron

Getting ready

How to do it...

How it works...

Creating a Desktop Application with Electron

Introduction

Setting up Electron with React

How to do it...

How it works...

Adding Node functionality to your app

How to do it...

How it works...

Building a more windowy experience

How to do it...

How it works...

Testing and debugging your app

How to do it...

How it works...

There's more...

Making a distributable package

How to do it...

How it works...

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Since its origins more than 20 years ago, JavaScript has evolved from a basic language designed to enhance web pages by adding some interactivity to them, to a full language that has been used to develop quite large, modern websites of very high complexity, with highly interactive behaviors and fast response times, that successfully challenge classic desktop applications. Not only has JavaScript become the tool for web development, it has also occupied a place in server development, starting to edge out more conventional languages and frameworks such as PHP, Java, and .NET, since developers can also use their JavaScript knowledge when working with Node. Finally, two other areas, mobile application and desktop program development, both previously reserved for specific languages, have also become part of JavaScript's wide range of tools.

Given this wide scope of JavaScript usage, in this book, we'll start by providing insights on the new features of the latest version of JavaScript, which can be applied everywhere, and also cover several modern tools that will help you with development. Then, we'll move on to using the language for specific areas, starting with the development of a services-based server, going on to create a web page that will use those services, then creating a mobile native version of the same web page, and ending up by producing a desktop executable program—each and every one of our products based on JavaScript and our set of tools.

Who this book is for

This book is for developers who want to explore the latest JavaScript features, frameworks, and tools for building complete web applications, including server- and client-side code. A basic working knowledge of JavaScript is required, and you will be introduced to the latest version, dated June 2018, to keep up with the latest developments and functionality in the language.

What this book covers

In this book, we will cover several subjects and the book is divided into five parts. In part one, in the first two chapters we'll get an overview of JavaScript tools and features:

Chapter 1

,

Working with JavaScript Development Tools

, is where we'll study and install several tools that will help our development, such as Visual Studio Code for development,

npm

for package management,

Git

for version control,

Prettier

for source code formatting,

ESLint

for code quality checks, and

Flow

for data type checks, among others.

Chapter 2

,

Using Modern JavaScript Features

, we will see how to use types in your code, and also go into more recent additions to JavaScript, dealing with strings, scopes, functions, async calls, class-oriented programming, modules, and even a touch of

Functional Programming

(

FP

).

In part two, the next three chapters, we'll move on to developing server-side code using Node, ending by writing a complete RESTful server:

Chapter 3

,

Developing with Node

, covers the basics of Node, and learn how to use JavaScript for server development. We'll cover themes such as streaming, accessing databases, and executing external processes, among others.

Chapter 4

,

Implementing RESTful Services with Node

, we'll see how to develop a server with

Express

, serving static files, and dealing with

Cross-Origin Resource Sharing

(

CORS

) permissions and with authentication rules, tying it all together by building a RESTful set of services.

Chapter 5

,

Testing and Debugging Your Server

, will teach you how to debug your code and write unit tests for it by using more tools, including

Winston, Morgan, Jest, Postman, and Swagger

.

After having worked on the server, we'll move to browsers, which makes up part three of this book. We devote the next five chapters to developing web applications with React and using the server we just developed as our backend, so we'll be going full stack with our development:

Chapter 6

,

Developing with React

, we'll learn about the

React

framework, set it up to use the development tools, and then we'll create a

Single Page Application

(

SPA

), which we'll expand in the following chapters.

Chapter 7

,

Enhancing Your Application

, deals with styling your application

with

SASS

and

StyledComponents

, making it adaptive and responsive, and covers accessibility and internationalization concerns.

Chapter 8

,

Expanding Your Application

, we'll see how to handle state with

Redux

, a powerful tool that will be necessary for larger-scale websites, and we'll also include topics such as routing, authorization, and code splitting for performance.

Chapter 9

,

Debugging Your Application

, we'll cover themes such as logging and using browser and standalone tools for enhanced debugging.

Chapter 10

,

Testing Your Application

, is where we will write unit tests for our code using Jest, and we'll also see how to use Storybook to simplify both development and testing.

It so happens that a variant of React, React Native, can be used to develop mobile applications, and that will be our next topic for the following two chapters which make up for part four of this book:

Chapter 11

,

Creating Mobile Apps with React Native

, we'll see how to install and use React Native to build a

mobile version of our web pages, which will work with different sized devices, in landscape or portrait mode, taking advantage of native features.

Chapter 12

,

Testing and Debugging Your Mobile App

, we'll cover how to debug and test our code, using some tools we have already seen, such as Jest and Storybook, plus a few new ones, specific for mobile development.

Finally in part five, for the last chapter of the book we'll use both our server and client-side knowledge, to develop native desktop applications with Electron:

Chapter 13

,

Creating a Desktop Application with Electron

, is where we'll see that we can use Electron together with the tools we have already seen, React and Node, to produce, debug, and test native desktop applications, which you can distribute to users, who will be able to install them on their own machines just as they'd do with any other desktop program.

To get the most out of this book

The book assumes you already have basic knowledge of JavaScript, and works up from there. Modern features of the language are explained, so we can develop code in the best way. Best practices for the language are also introduced and followed in all the code. Knowledge of HTML and CSS will also be required for the web and mobile applications.

All the code in the book runs on Windows, macOS, and Linux machines, so you shouldn't have any problems with regard to whatever computer you use. Some experience with terminal/command-line tools will come in handy, but most of the work will be done with a graphic interface.

Download the example code files

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

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

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

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Modern-JavaScript-Web-Development-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781788992749_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Keep in mind that you won't always be needing util.promisify()."

A block of code is set as follows:

// Source file: src/roundmath.js/* @flow */"use strict";//

continues..

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

// Source file: src/flowcomments.jslet someFlag

/*: boolean */

;let greatTotal

/*: number */

;let firstName

/*: string */

;function toString(x

/*: number */

)

/*: string */

{ return String(x);}let traffic

/*: "red" | "amber" | "green" */

;//

continues...

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

> npm install moment --save

> npm run addTypes

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "VSC provides full access to commands through its Command Palette... as seen in the following screenshot."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it...

This section contains the steps required to follow the recipe.

How it works...

This section usually consists of a detailed explanation of what happened in the previous section.

There's more...

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

There's more...

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Working with JavaScript Development Tools

The recipes we'll be seeing here are as follows:

Installing Visual Studio Code for development

Extending Visual Studio Code

Adding Fira Code font for better editing

Adding npm for package management

Doing version control with Git

Formatting your source code with Prettier

Documenting your code with JSDoc

Adding code quality checks with ESLint

Adding Flow for data types checks

Introduction

JavaScript has gone beyond a simple tool for adding small effects or behaviors to web pages, and has now become one of the world's most-used languages, applied to all sorts of developments. Given the complexity and variety of packages, libraries, and frameworks these days, you wouldn't start working without a full set of tools, and in this chapter we will aim to set up a good development environment, so you can work in a most efficient fashion.

Let's start by setting up some tools that will come in handy for all our JS development. It's been said that a bad craftsman blames his tools, so let's avoid even a hint of that by making some good choices!

Installing Visual Studio Code for development

The first tool we'll need is an Integrated Development Environment (IDE), or at least a powerful code editor. Some people make do with a simple editor, possibly something like vi or Notepad, but in the long run, all the wasted time in doing everything by hand doesn't pay. There are many options, such as (in alphabetic order) Atom, Eclipse, IntelliJ IDEA, Microsoft Visual Studio, NetBeans, Sublime Text, WebStorm, and Visual Studio Code. Personally, I've opted for the latter, though of course you may work perfectly well with any of the others.

The term IDE isn't really very well-defined. An IDE usually integrates many tools, providing a more seamless experience for the developer. Editors meant for development work provide some similar functionality by means of plugins or extensions. While this can certainly approximate the ease of use of an IDE, there may be some problems, such as a harder installation or configuration, or an interface that might be harder to figure out, but in the end, you may get practically the same feature set.

Visual Studio Code (VSC) is basically a source code editor, developed by Microsoft in 2015. Despite the similar name, it's not related to Microsoft's more powerful IDE, Visual Studio. The editor is free and open source, and the latest version is (currently) 1.29.1, dated November 2018, though new releases come out monthly. It can be used for JS development, but also for other languages, so if you wanted to, say, do your server-side coding in PHP, you could perfectly well use VSC for that too. However, from our point of view, the fact that VSC ships with IntelliSense for basically all the frontend languages (JS, TypeScript, JSON, HTML, CSS, LESS, SASS) is a good selling point. See https://code.visualstudio.com/docs/editor/intellisense for more on this.

A nice touch is that VSC is written in JS, based on Node, and packaged for the desktop by using the Electron framework. (We'll get to see these topics in Chapter 13, Creating a Desktop Application with Electron.) This automatically lets you use VSC in Linux, macOS, and Windows, which is a good advantage if you work in a team and not everybody shares the same development environment preferences.

A commonly held misconception is that VSC is based on the Atom editor. Though VSC shares the same editor component (Monaco), VSC itself is distinct from Atom. A source of this misunderstanding may be the fact that Electron, when created in 2013, was originally called Atom Shell; the name change to Electron happened in 2015.

In the past, I've worked extensively with Eclipse, Microsoft Visual Studio, and NetBeans. However, nowadays I work exclusively with VSC. Why do I prefer it? My reasons (your mileage may vary!) include the following:

Availability for multiple operating systems

: I personally use it on Mac and Linux all the time, and sometimes on Windows

Actively developed and maintained

: With updates (including bug fixes) provided on a regular basis

Very good performance

: VSC feels quite speedy

IntelliSense support

: Out of the box for all JS needs

Extensions available through plugins

: These become integrated into your work flow, adding new functionality

Integrated debugging

:As we'll see in

Chapter 5

,

Testing and Debugging Your Server

Integrated source code management

: Through Git (see the

Doing version control with Git

section, later)

Integrated terminal

: You can run commands or launch processes without leaving VSC

On the other hand, there are also some disadvantages; the main two being as follows:

The interface, configuration, and design of plugins usually varies from one to another, so you'll have to deal with frequent inconsistencies.

VSC has no knowledge of projects or the links between tools

needed

to create, for example, a

React

frontend application that communicates with a

Node

backend server. VSC at most recognizes folders, but how you organize them, and where you place your pieces of code, is totally up to you.

How to do it...

How do you install VSC? Instructions are different for each operating system, and may vary over time, so we'll just point you to downloading the appropriate package for your system at https://code.visualstudio.com/download, and following the correct platform-specific instructions at https://code.visualstudio.com/docs/setup/setup-overview. For Linux distributions, instead of downloading and installing some package by yourself, there may be another way out. For example, with OpenSUSE, there exists a repository that will allow you to install and update VSC through OpenSUSE itself; check out https://en.opensuse.org/Visual_Studio_Code for instructions on this, or https://code.visualstudio.com/docs/setup/linux for even more distribution-specific instructions.

If you want to live on the edge, and get to see new features as early as possible, there's also an Insiders build. You may install both the normal VSC stable build and the Insiders build, and work with whichever you prefer. Be warned, though, that you may find unexpected bugs, but you can help the VSC development team get rid of those by letting them know!

How it works...

After having installed it, open VSC and try out its settings to start configuring things the way you prefer, see the following screenshot. The bottom-left gear menu provides access to several related items, such as keyboard shortcuts, the color scheme, and icon set. If you have worked with VSC in the past, you'll have access to more recent files and folders:

The Welcome screen in VSC, and the settings gear at the bottom left

Configuring VSC is sort of unusual, but maybe to be expected, due to its JS origins. Basically, as seen in the following screenshot, you get a split screen, showing all the available configuration items (more than four hundred!) on the left, in JSON format, and you may change their values by writing new ones on the right side. If you mouse over any setting, you'll get to see the possible values, and you can select a new one just by clicking on it:

Configuring VSC is done by editing a JSON file with your personal choices
Do you want to pick a different editor for your work, or at least check out what's available out there? You may check out www.slant.co/topics/1686/~javascript-ides-or-editors for a long list of candidates, with pros and cons for each. At the current time (October 2018) the page shows 41 options, with Visual Studio Code at the top of the list.

One extra advantage of VSC has to do with updates. It will periodically check to see whether there's a new available version, and it will let you download and install it. (On the other hand, if you use Linux and install VSC through a repository, it may get updated automatically, without you even having to confirm it.) After that, you'll get an information screen with the changes for the last month; as seen in the following screenshot:

After each monthly update, you'll be informed of VSC's new features

Configuration of VSC goes beyond what we have just mentioned; see the following sections to find out more ways of extending its power and making it better for you to use.

Extending Visual Studio Code

VSC includes many out-of-the-box features, with which you can actually get started and working with no problems. By means of extensions, you can add support for languages, debugging, code quality, and many more functions. Configuring visual aspects is also provided, and you can change VSC's theme, shortcuts, and general preferences. However, you will want to add even more functionality to VSC, and that's where extensions (plugins) come in.

You can even develop your own extensions for VSC, though we won't be getting into that subject in this book. If you are interested, check out https://code.visualstudio.com/docs/extensions/overview. Extensions can be written in either JS or TypeScript (see the Adding Flow for data types checks section), and of course you can develop them by using VSC itself!

How to do it...

Extensions are optional installable additions to VSC, which provide specific new functions. Installing new extensions is a breeze. You can bring up the menu of all the available extensions by going to View | Extensions in the main menu (where you can also find a keyboard shortcut for it) or by clicking the Extensions icon at the bottom of the Activities bar at the left of VSC.

You will first get the list of currently installed extensions, as demonstrated in the following screenshot:

The list of already-installed extensions

If you want, you can disable any specific extension: click on it at the left side of the screen, and then click on Disable at the right. You can also fully uninstall any extension, and it's a sure bet that you'll do this quite a lot; the only way to find out if an extension works for you is by experimenting! Take a look at the following screenshot:

The VSC Marketplace is a good place to search for new extensions

Finding new extensions is also a breeze. You can either go to the VSC Marketplace at https://marketplace.visualstudio.com/ as seen in the preceding screenshot or directly search from within VSC, by typing in the search box, as seen in the following screenshot. I'd recommend paying attention to the total number of installs (the higher the better) and the rating from 1 to 5 stars (also, the higher the better). We'll be using several extensions; see, for example, in this chapter the Formatting your source code with Prettier and Documenting your code with JSDoc sections; there will be more in later chapters:

You can also search for new extensions from within VSC by just typing some keywords

Extensions are updated automatically, and you won't have to do much. Periodically, I'd recommend having a look at your list of extensions, and possibly searching again for new ones; there have been cases of new versions deprecating old ones, but with a new name, so an update wouldn't have worked. And, finally, be ready to experiment and find for yourself which extensions make you tick!

How to do it...

While there are many monospaced fonts (meaning all characters have the same width, which helps with onscreen alignment and indentation), there are not so many that also provide ligatures. In my case, after experimenting with many, I can recommend using Fira Code, available online at https://github.com/tonsky/FiraCode. This font provides lots of ligatures, not only for JS but for other programming languages as well. Take a look at following illustration for all the possibilities:

All the available ligatures, as seen in the figure taken from https://raw.githubusercontent.com/tonsky/FiraCode/master/showcases/all_ligatures.png

Download the latest version (1.206, as of December 2018) and install it, according to the standard procedures for your operating system. Afterwards, you'll have to change a pair of VSC settings, as seen earlier in this chapter; just add the following lines, and save your configuration:

"editor.fontFamily": "'Fira Code', 'Droid Sans Mono', 'Courier New'","editor.fontLigatures": true,...

The first line defines what font you want to use (and in CSS style, I also provided alternatives, just in case I took my settings to a different machine where Fira Code wasn't available) and the second line tells VSC to enable onscreen ligatures.

Adding npm for package management

When working either on the frontend or the backend, you will surely want to use already available libraries and frameworks, and that begets an interesting problem: how to deal with those packages' own needs, more packages, which themselves need even more packages, and so on. In Chapter 3, Developing with Node, we'll work with Node, but we need to get ahead of ourselves, and install npm (the package manager of Node) now to be able to set up several other tools.

npm also is the name of a gigantic repository of software, at https://www.npmjs.com/, which counts has around 600,000 packages you can observe that in the following screenshot and it grows at a daily rate of more than 500 packages, according to counts such as at http://www.modulecounts.com/, a place that tracks several well-known code repositories:

The growth of the npm repository seems exponential, according to data from www.modulecounts.com/

It can be safely said that it's probably impossible that a modern JS application doesn't require at least one, and more likely several, packages from npm, so adding a package manager will be mandatory; let's see a couple of them.

How to do it...

To get npm, you must first install Node, and that will come in handy for Chapter 3, Developing with Node, and the following ones. We won't copy the details here from the web (see https://docs.npmjs.com/getting-started/installing-node) but we can resume as follows:

Install

Node

, either by downloading it and then doing a manual installation (the most common way for Windows) or by adding an appropriate repository and then using your Linux package manager to install

Node

(that's the way I do this in my OpenSuse machines). Be careful, and pick the

Long Term Support

(

LTS

) version, recognizable by its even major number (such as 8.x.x, for example), unless you feel adventurous enough to use the latest development version, and you don't mind risks such as things stopping working!

Verify that

Node

is correctly installed. At the command line, type

node -v

and get the current version; in my machine, it's v9.7.1, but this will surely change by the time you try this out, and yes, I'm feeling adventurous and not using the LTS version!

Check if

npm

is up to its latest version with the

npm -v

command. If it's not (refer to the following code snippet), you'll have to update it:

> npm -v

5.5.1

────────────────────── │ │ │ Update available 5.5.1 → 5.7.1 │ │ Run npm i -g npm to update │ │ │ ──────────────────────

If you are working without a package manager (meaning you can get updates for your software automatically, without having to go and look for each on a one-by-one basis) you could also be interested in installing nvm, though it's optional; for more on this, see https://github.com/creationix/nvm.

How it works...

We'll be back to using npm in several places in this text. You'll have to use it in order to install several packages (some of which appear in this very chapter, such as JSDoc or Prettier) and later on we'll see how to configure an application, so all its required packages will be available and up to date.

You can find complete documentation for all npm features at https://docs.npmjs.com/.

Creating a project with npm

If you pick any empty directory and just install a package, you'll get some warnings related to a missing file, and you'll also find some new elements:

~ > md sample

~ > cd sample

~/sample > npm install lodash

npm WARN saveError ENOENT: no such file or directory, open '/home/fkereki/sample/package.json'

npm notice created a lockfile as package-lock.json. You should commit this file.

npm WARN enoent ENOENT: no such file or directory, open '/home/fkereki/sample/package.json'

npm WARN sample No description

npm WARN sample No repository field.

npm WARN sample No README data

npm WARN sample No license field.

+ [email protected]

added 1 package from 2 contributors and audited 1 package in 1.945s

found 0 vulnerabilities

~/sample> dir

total 4

drwxr-xr-x 3 fkereki users 20 Mar 15 11:39 node_modules

-rw-r--r-- 1 fkereki users 313 Mar 15 11:39 package-lock.json

What's happening here? Let's explain the results step by step, and then add whatever's missing. When you install modules, they (plus all their dependencies, and their dependencies' dependencies, and so on) are placed by default in a node_modules directory. This is a good measure, because all the code that will go in that directory is code that you haven't actually written, and that will eventually get updated by npm without your direct control. We can verify that quickly by going to the newly created directory and checking out its contents:

~/sample> cd node_modules

~/sample/node_modules> dir

total 36

drwxr-xr-x 3 fkereki users 20480 Mar 15 11:39 lodash

But, how would you control what packages (and their versions) are to be installed? That's the point of the missing package.json file, which, among other things that we'll meet later in the book, lets you specify what packages you want. (We'll also use it to specify parameters for other tools, such as Babel or ESLint, as we'll see later in this chapter.) You can create this file by hand, but it's easier to use npm init and just answer a few questions. This will create the required file, which will eventually describe all the dependencies of your project, plus other features (such as build or deploy procedures) that we'll see later:

~/sample> npm init

This utility will walk you through creating a package.json file.

It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields

and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and

save it as a dependency in the package.json file.

Press ^C at any time to quit.

package name: (sample) simpleproject

version: (1.0.0)

description: A simple project to show package.json creation

entry point: (index.js)

test command:

git repository:

keywords:

author: Federico Kereki

license: (ISC)

About to write to /home/fkereki/sample/package.json:

{

"name": "simpleproject",

"version": "1.0.0",

"description": "A simple project to show package.json creation",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "Federico Kereki",

"license": "ISC"

}

Is this ok? (yes)

Let's quickly go over each field, but remember these are only the basic ones; you can find more complete, official descriptions at https://docs.npmjs.com/files/package.json. As we skipped some answers, not all fields are present in the produced project file, but you can add everything later:

name

: Whatever name you want to assign to the project; by default, the directory's name.

version

: The semantic version number for your project. You would update this number whenever you create a newer version. See

https://semver.org/

for more information on semantic versioning.

description

: A simple description of your project, used by the

npm

search command.

main

: The name of the primary entry point to your program. It's common to use

index.js

for this.

test command

: A command (script) that you would run in order to execute unit tests for your code. We'll also be seeing this later in the book.

git repository

: If you are going to use source control, here you would give the details for it. We'll get to this in the

Doing version control with Git

section later in this chapter.

scripts

: This is an object that contains script commands you can run with

npm run

; for example, you could write scripts to build a project, deploy it, check it for code quality rules, and so on.

author

: Who created the project.

license

: Whatever license you want to assign to your project; this is meant for other people to know how they may use your package (permissions, restrictions) should you allow it. You can find a (quite long!) list of possible licenses at

https://spdx.org/licenses/

, and be careful when selecting one; there are legal aspects involved!

But, where are the packages? Let's see about that in the next section.

Installing packages for different purposes

There are two ways of installing npm packages: globally or locally:

If you plan to use the package from the command line, install it globally; for example,

npm install prettier -g

would install the

prettier

command so you can use it anywhere. (We'll see more of

prettier

in the

Formatting your source code with Prettier

section.) You may need to run the command as an administrator, or with

sudo

.

Otherwise, if you just need the package for your project, install it locally.

Installing packages locally can also be done in more than one way:

If you need the package for your own project, then you install it as a production package with

npm install lodash --save

Instead, if you need the package in order to build your project, but not as a part of the final, produced code, install it as a development package with

npm install eslint --save-dev

There are many shorthand versions for commands and options, such as just i for install, or -D for --save-dev, but I am more comfortable spelling everything out. If you want to learn more about this, just try npm --help.

After running these two latter commands, if you inspect package.json, you'll notice that some lines were added:

~/sample> cat package.json { "name": "simpleproject", "version": "1.0.0", "description": "A simple project to show package.json creation", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Federico Kereki", "license": "ISC",

"dependencies": {

"lodash": "^4.17.5"

},

"devDependencies": {

"prettier": "^1.11.1"

}

}

The dependencies and devDependencies entries refer to the production and development packages you require. If you are writing your software, and you decide you need a new package, there are two ways of doing this:

Add an entry to

package.json

, in the proper place, and then do

npm install

to get it

Alternatively, use

npm install

with either

--save

or

--save-dev

, and

package.json

will be updated by

npm

To remove a dependency, use npm uninstall instead. You must include --save or --save-dev in order to also remove the reference from package.json.

If you need specific versions, you will have to learn about semantic versioning. Version rules may become complex, and we'll just see the main ones; check https://docs.npmjs.com/files/package.json#dependencies and https://github.com/npm/node-semver#versions for a complete description:

4.5.6

Version 4.5.6, and none other

^4.0.0

Latest compatible version 4.x.x

^4.2.0

Latest compatible version 4.2.x

>5.6.7

A version greater than 5.6.7

~8.7.6

A version approximately equivalent to 8.7.6; should be 8.7.x

There's more...

Maintaining your packages and updating them is an important task, and if you are part of a development team, with people possibly even in different regions or countries, it becomes mandatory that everybody should be working with the same configuration at all times. If the project is very dynamic (meaning that packages will be added, removed, or updated frequently), npm can become a bit slow and also produce consistency or security problems; to address this situation, in 2016 Facebook released a new package manager, yarn. (See https://yarnpkg.com/en/.)

If you want to see the rationale for the changes, see the original blog post about yarn at https://code.facebook.com/posts/1840075619545360.

A key feature is that you can seamlessly replace npm with yarn, and just start using the latter, because it shares the same feature set (apart from some minor differences) while working in a faster, more reliable, and more secure way. For instance, yarn can manage downloads in parallel, and even work with cached packages, so it would even be possible to do some updates without a connection to the internet!

Installation is quite simple, and a bit ironic. Use npm with npm install -g yarn, and from that moment on, you will be able to use yarn directly and forget npm. See https://yarnpkg.com/en/docs/install for more complete documentation on the installation process.

For more details on comparing npm and yarn commands, check out https://yarnpkg.com/lang/en/docs/migrating-from-npm/ or https://shift.infinite.red/npm-vs-yarn-cheat-sheet-8755b092e5cc.

Doing version control with Git

In modern software development, it goes without saying that you will need some SCM (Software Configuration Management) software to keep track of all changes in your code. Today, the most-used tool is Git, which we'll also be using. Git was created in 2005 by Linus Torvalds (who also created Linux!) for the development of the Linux kernel; not a small task considering that its source is over 25 million lines of code!

Linux is not the only major operating system controlled with Git; in February 2017, Microsoft itself decide to migrate the development of Microsoft Windows to Git, and developed customizations to enhance remote work.

We won't be delving into how Git works, what commands to use, and so on, because that would be material enough for a book! We will focus on how to use Git with VSC. This is rather simple because not only was VSC written with Git access in mind, but there are also some extensions that can make work even easier, so you don't have to memorize lots of commands and options; take look at following illustration: