当前位置:网站首页>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
边栏推荐
- SAP ui5 objectpagelayout control usage sharing
- 关于vray5.2怎么关闭日志窗口
- Blockbuster: the domestic IDE is released, developed by Alibaba, and is completely open source!
- 【JS】提取字符串中的分数,汇总后算出平均分,并与每个分数比较,输出
- 风控模型启用前的最后一道工序,80%的童鞋在这都踩坑
- Honing · fusion | know that the official website of Chuangyu mobile terminal is newly launched, and start the journey of digital security!
- C语言活期储蓄账户管理系统
- uniapp
- 图片懒加载的方案
- What are the top ten securities companies? Is it safe to open an account online?
猜你喜欢
Talk about the understanding of fault tolerance mechanism and state consistency in Flink framework
赛克瑞浦动力电池首台产品正式下线
2022年化工自动化控制仪表考试试题及在线模拟考试
[paper reading] ckan: collaborative knowledge aware autonomous network for adviser systems
Do you really understand the things about "prototype"? [part I]
Comparative learning in the period of "arms race"
Learning note 4 -- Key Technologies of high-precision map (Part 2)
【Vite】1371- 手把手开发 Vite 插件
【DNS】“Can‘t resolve host“ as non-root user, but works fine as root
How can non-technical departments participate in Devops?
随机推荐
2022年T电梯修理操作证考试题及答案
Go project practice - Gorm format time field
Qt实现json解析
In wechat applet, after jumping from one page to another, I found that the page scrolled synchronously after returning
Atcoder beginer contest 254 "e BFS" f st table maintenance differential array GCD "
PWA (Progressive Web App)
中职组网络安全2021年江苏省省赛题目5套题目环境+解析全有需要的私信我
Pull up loading principle
[JS] array dimensionality reduction
LDAP overview
磨砺·聚变|知道创宇移动端官网焕新上线,开启数字安全之旅!
LSTM应用于MNIST数据集分类(与CNN做对比)
【JS】提取字符串中的分数,汇总后算出平均分,并与每个分数比较,输出
Web Components
Secteur non technique, comment participer à devops?
Go language-1-development environment configuration
Lazy loading scheme of pictures
基于昇腾AI丨爱笔智能推出银行网点数字化解决方案,实现从总部到网点的信息数字化全覆盖
vite//
Golang应用专题 - channel