当前位置:网站首页>Advanced scaffold development
Advanced scaffold development
2022-07-05 10:48:00 【Code Bruce Lee】
Advanced
Cli Command line tools
What are command line tools
Cmmand Line Inetrface, abbreviation cli, That is, the tools used in the command line terminal
effect
It greatly improves the development efficiency and quality
We can use these scaffolding tools to quickly build our project locally
Why study cli Command line tools
If you rely on it for a long time gui Finish all the work , Will miss Automation 、 Efficient engineering and other technical capabilities
Nor can you combine tools , Create customized macro tools
Create a command line custom command
Directory structure
|-szr-cli-code
|–bin
|—szr.js
|–package.json
To configure package.json
“bin”: {
“szr”: “./bin/szr.js”
}
Configure script compilation
// szr.js
#!/usr/bin/env node // It means that node Running in the environment
console.log(“szr190”)
Configure to environment variables
$ cd szr-cli-code
$ npm link
$ szr
$ szr190 // Printed content
Native receive command line parameters
/**
- return
- [
‘C:\Program Files\nodejs\node.exe’, // node Absolute path to the executable of
‘C:\Users\szr190\AppData\Roaming\npm\node_modules\szr-cli-code\bin\szr.js’ // Ongoing Javascript File path
] - Start with the third parameter : It is the parameter we pass in through the command line
/
console.log(process.argv)
Commander
cnpm install commander -S
// szr.js
const { program } = require(‘commander’)
program
.version(‘0.0.1’) // Set version
.usage(‘ [szr options]’)
.option(‘-cr, --classroom <custom classroom’s name>’, ‘current classroom name’, ‘szr190’) // command , Introduce , value
.command(‘add’, ‘add a szr template’)
.command(‘init’, ‘add a init desc’) // To configure Commands Commands and descriptions
.parse(process.argv) // szr -V / szr -h
inquirer
cnpm install inquirer -S
Basic use
const inquirer = require(‘inquirer’)
// Define the basic question and answer structure
// 1. Define the list of questions
const promptList = [
{
type: ‘input’,
message: ‘ user name ’,
name: ‘username’,
default: ‘szr190’
},
{
type: ‘input’,
message: ‘ Please enter 6 Bit code ’,
name: ‘password’,
validate: (val) => {
if (val.match(/^\d{6}$/ig)) {
return true
}
return “ Please enter 6 The number of digits ”
}
}
]
// 2. Get answers to questions
inquirer.prompt(promptList).then(answers => {
console.log(answers)
})
Mode or not
// Define whether to select the question list
const promptList = [
{
type: ‘confirm’,
message: ‘ Whether to use listening mode ’,
name: ‘watch’,
prefix: '’
},
{
type: ‘confirm’,
message: ‘ Whether to conduct batch monitoring of files ’,
name: ‘more-watch’,
suffix: ‘!’,
when: (answers) => {
if (answers.watch) {
return true
} else {
return false
}
}
}
]
// 2. Get answers to questions
inquirer.prompt(promptList).then(answers => {
console.log(answers)
})
Radio mode
// Define list radio mode
const promptList = [
{
type: ‘list’,
message: ‘ Please choose a single page front-end technology ’,
name: ‘technology’,
choices: [‘Vue’, ‘React’, ‘Angular’]
}
]
// 2. Get answers to questions
inquirer.prompt(promptList).then(answers => {
console.log(answers)
})
Multiple choice mode
// Define list multiple selection mode
const promptList = [
{
type: ‘checkbox’,
message: ‘ choice UI frame ’,
name: ‘ui’,
choices: [‘ElementUI’, ‘AntDesign Vue’, ‘Bootstrap Vue’, ‘Iview’]
// pageSize: 3
}
]
// 2. Get answers to questions
inquirer.prompt(promptList).then(answers => {
console.log(answers)
})
password & Text
// password & Text
const promptList = [
{
type: ‘password’,
message: ‘ Please input a password ’,
name: ‘pwd’
},
{
type: ‘editor’,
message: ‘ Please enter the comment text ’,
name: ‘bz’
}
]
// 2. Get answers to questions
inquirer.prompt(promptList).then(answers => {
console.log(answers)
})
ora
cnpm install ora -S
const ora = require(‘ora’)
const spinner = ora(‘ Start the download , Loading …’).start()
spinner.color = ‘green’
setTimeout(() => {
spinner.stop() // Stop loading
// spinner.succeed(‘ Congratulations on the successful download ’)
// spinner.fail(‘ Download failed !’)
// spinner.warn(‘ There is a problem downloading , Please check ’)
// spinner.info(‘ hello , You have a message ’)
}, 2500)
chalk
cnpm install chalk -S
const chalk = require(‘chalk’)
const log = console.log
log(chalk.red(‘szr190’)) // green yellow white gray/ bgRed background
// The paragraph
log(chalk Hello everyone , I am a {red.bold Szr190} )
download-git-repo
cnpm install download-git-repo -S
const download = require(‘download-git-repo’)
// download( Warehouse address , Local storage address , Options configuration , Callback function )
download(‘vuejs/awesome-vue’, ‘project/awe’, {
// clone: true,
// proxy: ‘’,
// headers: {},
// filetr: {}
}, (err) => {
if (err) {
throw new Error(‘error’)
} else {
console.log(‘ success ’)
}
})
Develop scaffolding process
1、 Create scaffold command
// szr.js
const { program } = require(‘commander’)
program
.version(‘1.0.0’)
.usage(‘<command [project options]>’)
.command(‘add’, ‘add a project template’)
.command(‘delete’, ‘delete project template’)
.command(‘list’, ‘list all’)
.command(‘init’, ‘generate a new project’)
.parse(process.argv)
2、 Create command executable
|-bin
|–szr-add.js
|–szr-delete.js
|–szr-init.js
|–szr-list.js
// package.json
“bin”: {
“szr”: “./bin/szr.js”,
“szr-add”: “./bin/szr-add.js”,
“szr-delete”: “./bin/szr-delete.js”,
“szr-list”: “./bin/szr-list.js”,
“szr-init”: “./bin/szr-init.js”
}
$ npm link // Mount to global
$ szr add/delete/init/list
3、add command
// szr-add.js
#!/usr/bin/env node
// Create a template , Store the user's question and answer information locally
// Introduce question and answer interaction module
const inquirer = require(‘inquirer’)
// Introduce file interaction system fs- File operation module
const fs = require(‘fs’)
// Introduce the path operation module path
const path = require(‘path’)
// Get template file
const tpath = path.resolve(__dirname, ‘…/szr-template.json’) // The root directory is created locally json Storage file
// Get the contents of the template list
let szrTlps = require(tpath) // The default is []
// Customized Q & a session
let questions = [
{
type: ‘input’,
name: ‘tpl-name’,
message: ‘ Please enter the template name ’,
// verification : Must input , And can't repeat
validate: (val) => {
if (!val) return ‘ Template name cannot be empty ’
if (szrTlps.filter(v => (v.name === val)).length > 0) return ‘ The current template already exists ’
return true
}
},
{
type: ‘input’,
name: ‘tpl-url’,
message: ‘ Please enter the address of the template ’,
// verification : Must input
validate: (val) => {
if (!val) return ‘ Template address cannot be empty ’
return true
}
}
]
// Interactive Q & A , Information processing
inquirer
.prompt(questions)
.then(answers => {
// Get questions and answers
let tplName = answers[‘tpl-name’]
let tplUrl = answers[‘tpl-url’]
// Update to szr-template Go to the template file
szrTlps.push({
name: tplName,
url: tplUrl
})
// Update file content
fs.writeFileSync(tpath, JSON.stringify(szrTlps))
})
4、delete command
// szt-delete.js
#!/usr/bin/env node
// Introduce question and answer interaction module
const inquirer = require(‘inquirer’)
// Introduce file interaction system fs- File operation module
const fs = require(‘fs’)
// Introduce the path operation module path
const path = require(‘path’)
// Get template file
const tpath = path.resolve(__dirname, ‘…/szr-template.json’)
// Get the contents of the template list
let szrTlps = require(tpath) // The default is []
// introduce chalk
const chalk = require(‘chalk’)
let questions = [
{
type: ‘input’,
name: ‘tpl-name’,
message: ‘ Please enter the name of the template to delete ’,
// verification : Must input , And can't repeat
validate: (val) => {
if (!val) return ‘ Template name cannot be empty ’
if (szrTlps.filter(v => (v.name === val)).length == 0) return ‘ The template currently to be deleted does not exist ’
return true
}
}
]
// Interactive Q & A , Information processing
inquirer
.prompt(questions)
.then(answers => {
// Get questions and answers
let tplName = answers[‘tpl-name’]
// Update file content
fs.writeFileSync(tpath, JSON.stringify(szrTlps.filter(v => (v.name !== tplName))))
// Print success message
console.log(chalk.green(‘ Delete successful ’))
})
5、list command
// szr-list.js
#!/usr/bin/env node
// Introduce file interaction system fs- File operation module
const fs = require(‘fs’)
// Introduce the path operation module path
const path = require(‘path’)
// Get template file
const tpath = path.resolve(__dirname, ‘…/szr-template.json’)
// Get the contents of the template list
let szrTlps = require(tpath) // The default is []
// introduce chalk
const chalk = require(‘chalk’)
szrTlps.forEach(v => {
console.log(chalkTemplate name :{green ${v.name}}, Template address :{red ${v.url}})
})
6、init command
// szr-init.js
#!/usr/bin/env node
// Introduce the command line module
const { program } = require(‘commander’)
// Introduce remote download module
const download = require(‘download-git-repo’)
// Load module
const ora = require(‘ora’)
// Introduce file interaction system fs- File operation module
const fs = require(‘fs’)
// Introduce the path operation module path
const path = require(‘path’)
// Get template file
const tpath = path.resolve(__dirname, ‘…/szr-template.json’)
// Get the contents of the template list
let szrTlps = require(tpath) // The default is []
// introduce chalk
const chalk = require(‘chalk’)
// Define the order szr init [project name]
program
.usage(‘ [project-name]’)
.parse(process.argv)
// When there are no input parameters , namely : Use it directly szr When ordered
if (program.args.length < 1) {
program.help()
} else {
// Get the parameters entered by the user
let tName = program.args[0]
let pName = program.args[1]
// console.log(tName, pName)
if (szrTlps.filter(v => (v.name === tName)).length === 0) { // Whether the input is in szr-template.json in
console.log(chalk.red(‘ Template name does not exist , Please use szr list Command to view the inputable templates ’))
} else if (!pName) { // Verify whether the entered project name exists
console.log(chalk.red(‘ The project folder name cannot be empty ’))
} else {
// Get template address
let url = szrTlps.filter(v => (v.name === tName))[0].url
// Start project creation
console.log(chalk.yellow(‘ Start project creation ’))
// Create load icon
const spinner = ora(‘ Downloading and pulling …’)
spinner.start()
// Pass in parameters to download
download(‘direct:’ + url, pName, { clone: true }, err => {
if (err) {
spinner.fail()
console.log(chalk.red(‘ Failed to create directory ’ + err))
return
}
// Successfully loaded
spinner.succeed()
console.log(chalk.green(‘ Successfully created Directory ’))
})
}
}
npm Release && Global installation uses
$ touch .npmignore // add to ignore Ignore files
$ touch README.md // add to md file , Describe
$ npm publish // Input npm Account and password of , You may also need to use the mailbox to get the login string
$ npm i szr-cli-code -g
$ szr
$ szr list
$ szr delete
$ szr add
$ szr init cli-test-demo cli-project
边栏推荐
猜你喜欢

DGL中的消息传递相关内容的讲解

磨砺·聚变|知道创宇移动端官网焕新上线,开启数字安全之旅!

Go-3-the first go program

Learning Note 6 - satellite positioning technology (Part 1)

Based on shengteng AI Yisa technology, it launched a full target structured solution for video images, reaching the industry-leading level

The first product of Sepp power battery was officially launched

Web3 Foundation grant program empowers developers to review four successful projects

重磅:国产IDE发布,由阿里研发,完全开源!

How can non-technical departments participate in Devops?

Pseudo class elements -- before and after
随机推荐
Honing · fusion | know that the official website of Chuangyu mobile terminal is newly launched, and start the journey of digital security!
Crawler (9) - scrape framework (1) | scrape asynchronous web crawler framework
What are the top ten securities companies? Is it safe to open an account online?
关于vray 5.2的使用(自研笔记)(二)
csdn软件测试入门的测试基本流程
GBase 8c数据库如何查看登录用户的登录信息,如上一次登录认证通过的日期、时间和IP等信息?
谈谈对Flink框架中容错机制及状态的一致性的理解
websocket
Have the bosses ever encountered such problems in the implementation of flinksql by Flink CDC mongdb?
5G NR系统架构
Golang应用专题 - channel
SqlServer定时备份数据库和定时杀死数据库死锁解决
Broyage · fusion | savoir que le site officiel de chuangyu mobile end est en ligne et commencer le voyage de sécurité numérique!
2021年山东省赛题库题目抓包
How can non-technical departments participate in Devops?
Web Components
第五届 Polkadot Hackathon 创业大赛全程回顾,获胜项目揭秘!
使用GBase 8c数据库过程中报错:80000502,Cluster:%s is busy,是怎么回事?
A usage example that can be compatible with various database transactions
The first product of Sepp power battery was officially launched