The NPM command line interface (CLI) tool is a new tool for node. js.

  • Not familiar with NPM tools and Node scripts
  • Don’t know how to make a generic CLI tool
  • Simply publish and use NPM packages

Tips: This is a relatively old knowledge system written two years ago, the old article, only used for new literacy. Complete source code repository address ziyi2/ npm-CLI-package.

Service section can view Express application framework based on the selection of technical solutions.

The Node script

Node scripting commands are often used in projects to simplify development efforts, such as the NPM scripting command build:file for Element component libraries (use scripts to generate entry source files for Webpack builds).

Simple Node scripting commands can solve the immediate problem, but if the implementation is relatively complex and multi-user reuse (such as binding scaffolding or multi-copy reuse) can cause the following problems:

  • Poor maintenance (maintenance of historical features/dependencies/versions, etc.)
  • Pollution Project folder
  • Increased development communication costs

Tips: As the interviewer often can see the resume written development or maintenance of XXX component, at this time will simply ask how to reuse the component, there will be some interviewees answer manual copy…

To solve the problems caused by Node script commands, you can use the NPM package to implement the common CLI tool package.

NPM package manager

The NPM package manager allows users to upload their own generic packages or CLI tools to the NPM server. Other developers only need to download and install the CLI tool to use it locally.

Note that NPM packages can be installed locally or globally. Local installation allows you to add published CLI tools to your project’s development dependency list. Global installation links the commands of the NPM CLI tool to the global execution environment.

Tip: Using a local installation is more likely to be used in conjunction with NPM scripts in a project, and a feature version of the solidified tool. Global installation is more about initialization functions, such as VUE – CLI, create-react-app, express-Generator, etc. Node scripts are not implanted in the project, but stored in the user folder of the operating system.

Common CLI tools are as follows:

  • npm/cli
  • babel/cli
  • webpack/webpack-cli
  • vuejs/vue-cli
  • commitizen/cz-cli

The following details how to build, publish, install, and use a simple CLI tool.

CLI tool

build

First, create the project file of the NPM CLI tool. Run the NPM init command to create the package.json description file. Enter the project name, version, description, and project entry file. This information is mainly used to publish library package), author information, etc. :

AppledeMacBook-Pro:npm-cli-package ziyi2$ 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: (npm-cli-package) 
version: (1.0. 0Entry point: (index.js) Test command: Git repository: (HTTPS://github.com/ziyi2/npm-cli-package.git) 
keywords: npm cli
author: ziyi2
license: (ISC) 
About to write to /Users/ziyi2/Git/npm-cli-package/package.json:

{
  "name": "npm-cli-package"."version": "1.0.0"."description": "NPM CLI Tool release and Use"."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git"."url": "git+https://github.com/ziyi2/npm-cli-package.git"
  },
  "keywords": [
    "npm"."cli"]."author": "ziyi2"."license": "ISC"."bugs": {
    "url": "https://github.com/ziyi2/npm-cli-package/issues"
  },
  "homepage": "https://github.com/ziyi2/npm-cli-package#readme"
}


Is this OK? (yes) 
Copy the code

Tip: NPM itself is a CLI tool.

The package.json description file generated after input information is as follows:

{
  "name": "npm-cli-package"."version": "1.0.0"."description": "NPM CLI Tool release and Use"."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git"."url": "git+https://github.com/ziyi2/npm-cli-package.git"
  },
  "keywords": [
    "npm"."cli"]."author": "ziyi2"."license": "ISC"."bugs": {
    "url": "https://github.com/ziyi2/npm-cli-package/issues"
  },
  "homepage": "https://github.com/ziyi2/npm-cli-package#readme"
}

Copy the code

Next, you need to configure the executable file of the PATH PATH. Configure the bin property in package.json, which corresponds to the PATH of the executable file. For example, set the executable file path corresponding to bin to SRC /index.js under the current project:

"bin": {
   // npm-cli-package is an executable command that points to the SRC /index.js script
   // The environment interpreter for this script is not yet clear
   "npm-cli-package": "src/index.js"
 },
Copy the code

Tips: When you run the NPM link or install the CLI tool, the NPM creates a soft link for the bin configuration file. For Windows, the default global installation will be in the C:\Users\{username}\AppData\Roaming\ NPM directory, local installation will be in the project./node_modules/. Bin directory.

After configuring the module path for the bin property, you can start designing the executable. To make the entry file use Node as an interpreter, write #! To the file header. /usr/bin/env node, the purpose of which is to use env to find the node startup path in the operating system and to use Node as the environment interpreter for the executable file. For example, write a Node script that prints information in the SRC /index.js entry file:

#! /usr/bin/env node
console.info('NPM - cli - package:.'1.0.0')
Copy the code

Tips: Env contains some environment variables, including the execution paths of some of our installed software, so you can use env to find Node execution paths on different operating systems so that files can be interpreted and executed properly.

Soft links

After the CLI tool is designed, the next step is to test whether it can be used normally. At this time, you can use the NPM link command to link it to the global execution environment, so that you can use the CLI tool in any path in the system. Execute NPM link:

// Windows
PS C:\Users\ziyi2\Desktop\npm-cli-package> npm link
up to date in 0.428s
C:\Users\ziyi2\AppData\Roaming\npm\npm-cli-package -> C:\Users\ziyi2\AppData\Roaming\npm\node_modules\npm-cli-package\src\index.js
C:\Users\ziyi2\AppData\Roaming\npm\node_modules\npm-cli-package -> C:\Users\ziyi2\Desktop\npm-cli-package

// MAC OS X
AppledeMacBook-Pro:npm-cli-package ziyi2$ npm link
npm notice created a lockfile as package-lock.json. You should commit this file.
up to date in 4.113s
found 0 vulnerabilities

/usr/local/bin/npm-cli-package -> /usr/local/lib/node_modules/npm-cli-package/src/index.js
/usr/local/lib/node_modules/npm-cli-package -> /Users/ziyi2/Git/npm-cli-package
Copy the code

When NPM link is executed, you can see that the command does two main things on a Mac:

  • Is an executable filesrc/index.jsCreate a soft link and link it to/usr/local/bin/<package>(under WindowsC:\Users\{username}\AppData\Roaming\npm\<package>
  • Create a soft link for the current project and link it to/usr/local/lib/node_modules/<package>(under WindowsC:\Users\{username}\AppData\Roaming\npm\node_modules\<package> )

Therefore, when the bin command is executed in the global environment, Node is enabled to execute the corresponding executable file.

Note: If bin does not specify the command name, the

field in pageage.json is used as the command by default.

At this point, run the NPM -cli-package command anywhere:

Appledemacbook-pro: NPM -cli-package ziyi2$NPM -cli-package NPM -cli-package NPM -cli-package1.0. 0
Copy the code

You can see that any path outside the current project can be successfully printed using this command, indicating that the Node interpreter and soft link are successfully set up.

Tips: In Windows, you can view the soft link of npm-cli-package in the user directory C:\Users\{username}\AppData\Roaming\ NPM \node_modules. NPM -cli-package (Shell) and NPM -cli-package. CMD (CMD) can be found in C:\Users\{username}\AppData\Roaming\ NPM.

release

Through the USE of NPM link and command line tests, we found that the design of the tool has no problems. If you want to share it with others, you can use the publishing mechanism of NPM package manager. Before publishing tools, you need to register an account on the NPM website. After successful registration, use NPM login in the command terminal to link to your registered account (NPM login will save the certificate information of the login account in the local computer, so there is no need to login to the account again), and at the same time, it will generate the token information of your current login in the website of NPM. After login, you can run the NPM whoami command to view the current account name.

Warm prompt: don’t use NPM taobao mirror address login, you need to use NPM official address, can use NPM config set command set to NPM registry https://registry.npmjs.org/ official release package address.

AppledeMacBook-Pro:~ ziyi2$ npm login
Username: ziyi222
Password: 
Email: (this IS public) 673191402@qq.com
Logged in as ziyi222 on https://registry.npmjs.org/.
Copy the code

After login, the token information is generated on the NPM official website. Then, run the NPM publish command to publish the CLI tool:

Appledemacbook-pro: NPM -cli-package ziyi2$NPM -cli-package NPM -cli-package NPM -cli-package1.0. 0Appledemacbook-pro: NPM -cli-package ziyi2$NPM publish NPM notice NPM notice 📦 NPM -cli-package@1.0. 0
npm notice === Tarball Contents === 
npm notice 595B   package.json
npm notice 12.1kB README.md   
npm notice 64B    src/index.js
npm notice === Tarball Details === 
npm notice name:          npm-cli-package                         
npm notice version:       1.0. 0                                   
npm notice package size:  5.1 kB                                  
npm notice unpacked size: 12.8 kB                                 
npm notice shasum:        624e3e45667da53d474418907d3250336b56208b npm notice integrity: sha512-b77RbfmmF+Gjf[...] MSbp9PL4UUE9w== npm notice total files:3                                       
npm notice 
+ npm-cli-package@1.0. 0
Copy the code

If you check your personal account information on the NPM official website, you can find that version 1.0.0 of the tool has been released. If you want to publish the Scope package, you need to create an organization on the NPM official website (for example, here we use the account ziyi222 as an organization, then rename the account ziyi222 to Ziyi222222 and log in again) :

AppledeMacBook-Pro:npm-cli-package ziyi2$ npm login
Username: ziyi222222
Password: 
Email: (this IS public) 673191402@qq.com
Logged in as ziyi222222 on https://registry.npmjs.org/.
Copy the code

Modify the package.json configuration file again:

{
  "name": "@ziyi222/npm-cli-package".// ...
  "publishConfig": {
    "access": "public"}}Copy the code

Publish with NPM:

Appledemacbook-pro: NPM -cli-package ziyi2$NPM publish NPM notice NPM notice 📦 @ziyi222/ NPM -cli-package@1.01.
npm notice === Tarball Contents === 
npm notice 653B   package.json
npm notice 12.1kB README.md   
npm notice === Tarball Details === 
npm notice name:          @ziyi222/npm-cli-package                
npm notice version:       1.01.                                   
npm notice package size:  5.1 kB                                  
npm notice unpacked size: 12.8kB npm notice shasum: fac560a42c43d276c9fee17c21887bedaf34bad1 npm notice integrity: sha512-j/QScEgX+glfS[...] OxhhZcIavUhfg== npm notice total files:2                                       
npm notice 
+ @ziyi222/npm-cli-package@1.01.
Copy the code

Installation and use

The developer installs the tool globally using the NPM install command:

AppledeMacBook-Pro:npm-cli-package ziyi2$ npm install npm-cli-package -g
/usr/local/bin/npm-cli-package -> /usr/local/lib/node_modules/npm-cli-package/src/index.js
+ npm-cli-package@1.0. 0
updated 1 package in 12.977s
Copy the code

According to the installation information, the final CLI tool script links to /usr/local/bin/npm-cli-package. After the installation is successful, you can use the COMMANDS specified by the CLI in your project.

The last

This is just a simple tutorial example, but a truly designed CLI tool might need to consider some of the following features:

  • Help information: Displays supported commands and option parameters
  • Version information: Indicates the current CLI version
  • Environment detection: Used to check the current supported interpreter (Node) version, etc
  • Interactive panel: Provides options for the current command
  • Information printing: provides printing information in various semantic colors
  • .

So you may need a dependency library for additional functionality, such as:

  • commander.js – node.js command-line interfaces made easy
  • chalk – Terminal string styling done right
  • Inquirer – A collection of common interactive command line user interfaces
  • node-semver – The semver parser for node (the one npm uses)
  • .

The real power of designing CLI tools is that you can take advantage of all the capabilities supported by Node (such as common file systems, HTTP services, etc.), giving developers a variety of possibilities:

  • For example, a one-click scaffolding project
  • For example, one click to generate/change source files
  • For example, various management platforms (such as Mock, I18N, theme package management, etc.) that provide open apis can be used to synchronize information between local projects and platforms
  • For example, one click to generate Webpack/Babel/Git Hook configuration file information
  • .

In addition, if the DESIGNED CLI tool is not friendly to developers, a graphical interface tool similar to Vue UI can also be designed to enhance users’ development experience (for example, I designed a LEGO UI tool with my colleagues to generate the classic layout page of the project with one click).

Recruitment tips (telephone pole infertility series)

Hi, everyone, we are the newly established BU Government affairs Nail Business Department of Alibaba (the health code students in Hangzhou are using is a project jointly designed by BU and other BU). There are still a large number of Web front-end positions available. If you want to find me or want to know more information about recruitment, you can add me on wechat: 18768107826