Book Image

Modern JavaScript Web Development Cookbook

By : Federico Kereki
Book Image

Modern JavaScript Web Development Cookbook

By: Federico Kereki

Overview of this book

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.
Table of Contents (15 chapters)

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:

  1. 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!
  2. 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!
  3. 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.