Create Your Own Yeoman-Style Scaffolding Tool with Caporal.js

Create Your Own Yeoman-Style Scaffolding Tool with Caporal.js

Starting a new project (especially as a JavaScript developer) can often be a repetitive and tedious process. For each new project, we normally need to add a package.json file, pull in some standard dependencies, configure them, create the correct directory structure, add various other files … The list goes on.

But we’re lazy developers, right? And luckily we can automate this. It doesn’t require any special tools or strange languages — if you already know JavaScript, the process is actually quite simple.

In this tutorial, we are going to use Node.js to build a cross-platform command-line interface (CLI). This will allow us to quickly scaffold out a new project using a set of predefined templates. It will be completely extensible so that you can easily adapt it to your own needs and automate away the tedious parts of your workflow.

Why Roll Your Own?

Although there are plenty of similar tools for this task (such as Yeoman), by building our own we gain knowledge, experience and can make it totally customizable. You should always consider the idea of creating your tools over using existing ones, especially if you are trying to solve specialized problems. This might sound contrary to the common practice of always reusing software, but there are cases where implementing your own tool can be highly rewarding. Gaining knowledge is always helpful, but you can also come up with highly personalized and efficient tools, tailored especially to your needs.

Saying that, we won’t be reinventing the wheel entirely. The CLI itself is going to be built using a library called Caporal.js. Internally it will also use prompt to ask for user data and shellJS that will provide us with some Unix tools right in our Node.js environment. I selected these libraries mostly because of their ease of use, but after finishing this tutorial, you’ll be able to swap them out for alternatives that best fit your needs.

As ever, you can find the completed project on Github: https://github.com/sitepoint-editors/node-scaffolding-tool

Now let’s get started …

Up and Running with Caporal.js

First, create a new directory somewhere on your computer. It is recommended to have a dedicated directory for this project that can stay untouched for a long time since the final command will be called from there every time.

Once in the directory, create a package.json file with the following content:

{
  "name": "scaffold",
  "version": "1.0.0",
  "main": "index.js",
  "bin": {
    "scaffold": "index.js"
  },
  "dependencies": {
    "caporal": "^0.3.0",
    "colors": "^1.1.2",
    "prompt": "^1.0.0",
    "shelljs": "^0.7.7"
  }
}

This already includes everything we need. Now to install the packages execute npm install and all the marked dependencies will be available in our project. The versions of these packages are the latest at the time of writing. If newer versions become available in the meantime, you might consider updating them (paying attention to any API changes).

Note the scaffold value in bin. It indicates the name of our command and the file that is going to be called every time we enter that command in our terminal (index.js). Feel free to change this value as you need.

Building the Entry Point

The first component of our CLI is the index.js file which contains a list of commands, options and the respective functions that are going to be available to us. But before writing this file, let’s start by defining what our CLI is going to do in a little more detail.

  • The main (and only) command is create, which allow us to create a project boilerplate of our choice.
  • The create command takes a mandatory template argument, that indicates which template we want to use.
  • It also takes a --variant option that allows us to select a specific variation of our template.
  • If no specific variant is supplied, it will use a default one (we will define this later).

Caporal.js allows us to define the above in a compact way. Let’s add the following content to our index.js file:

#!/usr/bin/env node

const prog = require('caporal');

prog
  .version('1.0.0')
  .command('create', 'Create a new application')
  .argument('<template>', 'Template to use')
  .option('--variant <variant>', 'Which <variant> of the template is going to be created')
  .action((args, options, logger) => {
    console.log({
      args: args,
      options: options
    });
  });

prog.parse(process.argv);

The first line is a Shebang to indicate that this is a Node.js executable.

The shebang included here only works for Unix-like systems. Windows has no shebang support, so if you want to execute the file directly on Windows you will have to look for a workaround. Running the command via npm (explained at the end of this section) will work on all platforms.

Next, we include the Caporal.js package as prog and we start defining our program. Using the command function, we define the create command as the first parameter and a little description as the second one. This will be shown in the automatically-generated help option for our CLI (using --help).

Then, we chain the template argument inside the argument function, and because it is a required argument we wrap it inside angular brackets (< and >).

We can define the variant option by writing --variant <variant> inside the option function. It means that the option for our command is called --variant and the value will be stored in a variant variable.

Finally, in the action command we pass another function that will handle the current command. This callback will be called with three arguments:

  • passed arguments (args)
  • passed options (options)
  • a utility object to show things on screen (logger).

Continue reading %Create Your Own Yeoman-Style Scaffolding Tool with Caporal.js%


Source: Sitepoint