The main steps
- Create a folder, create a JS file (here named index.js), and enter the JS code you want to execute. Note that the Node development command line tool declaration must be added at the top:
#! /usr/bin/env node
- The input terminal
npm init -y
Create package. Json
For example: I want to type ‘voe’ to execute the index.js file, what do I need to do?
- First, add in package.json
"bin":{"voe":"index.js"}
- Step two, terminal input
npm link
, global register, so that any directory on the computer can type ‘voe’ to execute the index.js file
- Install the commander:
npm install commander
Commander url.
- Add Commander to index.js,
const {program} = require('commander)
For example, if you want to download a Gitee repository from the command line (I’m using the code cloud here, build a few test repository templates in your Gitee repository)
-
NPM install download-git-repo const download = require(‘download-git-repo’)
-
Second, write your new repository template address and download address to index.js
-
Step 3: Download the template you need. One of the templates I created in Gitee here is called Tpl-A. After downloading, the template is called AAA. The terminal type voe init tpl-A AAA
- Installing the Template Enginehandlebars.
npm install handlebars
And compile the package.js file here in index.js
const packageContent = fs.readFileSync(`${projectName}/package.json`.'utf-8')
const packageResult = handlebars.compile(packageContent)(answers)
Copy the code
- The installation wizardinquirer
npm install inquirer
Create package.json file in the TPL-A template and set the contents of the wizard you want. I have set three of them here.
{
"name": "{{name}}"."version": "1.0.0"."description": "{{description}}"."scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": []."author": "{{author}}"."license": "ISC"."bin": {
"hnz": "index.js"
},
"dependencies": {
"commander": "^ 5.1.0"."download-git-repo": "^ 3.0.2." "}}Copy the code
The final effect is shown below, with the setup wizard appearing
- Do YOU want to read and write what you entered during the wizard? That’s where dependency FS comes in,
const fs = require('fs')... .// Parse and replace the collected user input data into package.json file
const packagePath = `${projectName}/package.json`
const packageContent = fs.readFileSync(`${projectName}/package.json`.'utf-8')
constpackageResult = handlebars.compile(packageContent)(answers) fs.writeFileSync(packagePath, packageResult) ... .Copy the code
Voe init TPL -a KKK download template successfully open package.json file will be different ~
The final code is as follows:
#! /usr/bin/env node
// Javascript scripts executed using node command-line tools must have #! At the top. The/usr/bin/env node statement
//1. Obtain the user input command
// Native fetch
const { program } = require('commander')
const download = require('download-git-repo')
const handlebars = require('handlebars') // Template engine
const inquirer = require('inquirer') / / the wizard
const fs = require('fs')
program.version('0.1.1') // The version number is displayed when -v or --version is used
// Voe innit a a-name is initialized based on a project
// Voe innit b b-name Is initialized based on the B project
const templates = {
'tpl-a': {
url: 'https://gitee.com/beth_work/tpl-a'.downloadUrl: 'https://gitee.com:beth_work/tpl-a#master'.description: 'a template',},'tpl-b': {
url: 'https://gitee.com/beth_work/tpl-b'.downloadUrl: 'https://gitee.com:beth_work/tpl-b#master'.description: Template 'b',
},
}
program
.command('init <template> <project>')
.description('Initialize the project template')
.option('-s, --setup_mode [mode]'.'Which setup mode to use')
.action(function (templateName, projectName) {
// Download the corresponding template based on the template name and name it projectName
console.log(templates[templateName])
const { downloadUrl } = templates[templateName]
//download
// First argument: warehouse address, second argument: download path
download(downloadUrl, projectName, { clone: true }, (err) => {
if (err) {
return console.log(err ? err : 'Success')}// Read the package.json file under the project
// Use the wizard to collect the values entered by the user
// Use a template engine to parse user input data into package.json files
// After parsing, write the parsed result into package.json file
inquirer
.prompt([
/* Pass your questions in here */
{ type: 'input'.name: 'name'.message: 'Please enter project name' },
{ type: 'input'.name: 'description'.message: 'Please enter project profile' },
{ type: 'input'.name: 'author'.message: 'Please enter author name' },
])
.then((answers) = > {
// Use user feedback for... whatever!!
// Parse and replace the collected user input data into package.json file
const packagePath = `${projectName}/package.json`
const packageContent = fs.readFileSync(`${projectName}/package.json`.'utf-8')
const packageResult = handlebars.compile(packageContent)(answers)
fs.writeFileSync(packagePath, packageResult)
console.log('Template initialization successful')
})
.catch((error) = > {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else when wrong
}
})
})
})
program
.command('list')
.description('View all available templates')
.action((a)= > {
for (let key in templates) {
console.log(`${key} ${templates[key].description}`)
}
})
program.parse(process.argv)
Copy the code
Visual beautification
- ora & chalk & log-symbols
NPM package, so everyone can use your template ~
npm install -global voe-cli
1. Register an NPM account. 2. Change the name in package.json to your own package name (voe-cli)
Ps: This name is independent of the local project name
- Open the terminal and enter:
npm login
Login NPM - Run the command after successful login
npm publish
Ps: There is a pit here for the following reasons:
- Your NPM account is not logged in to the terminal;
- The mailbox is not verified;
- Your NPM has a Taobao mirror set
Check whether the warehouse is set into taobao image libraries NPM config get registry, if it is, if so, set back to the original warehouse NPM config set registry=http://registry.npmjs.org
- After the release is successful, set back to the original Taobao image
npm config set registry=https://registry.npm.taobao.org/
NPM will search for your package in a few minutes
NPM I –global voe- CLI