NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
[TOC] # 开发全局包-命令行工具 ## 1,创建一个npm包 ## 2, packpage.josn设置命令和指定处理命令的文件 - 设置**bin**参数 ``` { "name": "mulo-cli", "version": "1.0.1", "description": "mulo code build tools", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "bin": { "mulo": "./bin/mulo.js" }, "keywords": [ "mulo" ], "author": "", "license": "ISC", "dependencies": { "commander": "^3.0.0", "mulo-cli-ui": "^0.1.4", "semver": "^6.3.0" }, "engines": { "node": ">=8.9" } } ``` ``` //本地开发全局包命令,将编辑的包安装到全局 npm link ``` ## 添加命令 - 头部声明这个文件用none执行 ``` #!/usr/bin/env node const program = require('commander') //指定版本号 program.version('0.0.1', '-v, --version') //help命令后缀操作 program.on('--help', function () { console.log('no help can use') }); program.command('create <app-name>') //说明 .description('create a new project') //处理函数 .action((name, cmd) => { console.log('your app name is ' + name); console.log('your cmd is ' + cmd); }) /** * 测试命令 * @demo mulo ui * */ program .command('test [paths...]') .description('我的第一个自定义命令') .option('--mode <mode>') //参数声明, 参数说明 //参数声明规则: 参数名 <参数> .option('--rule <ruleName>', 'inspect a specific module rule') .option('--plugin <pluginName>', 'inspect a specific plugin') .option('--rules', 'list all module rule names') .option('--plugins', 'list all plugin names') .option('-v --verbose', 'Show full function definitions in output') .action((paths, cmd) => { var args = cleanArgs(cmd); console.log(paths); console.log(args); }) //-------------------- 辅助函数 /** * 读取参数 * * @param {} cmd */ function cleanArgs(cmd) { const args = {} cmd.options.forEach(o => { const key = camelize(o.long.replace(/^--/, '')) // if an option is not present and Command has a method with the same name // it should not be copied if (typeof cmd[key] !== 'function' && typeof cmd[key] !== 'undefined') { args[key] = cmd[key] } }) return args } /** * 读取参数名称 * @param {*} str */ function camelize(str) { return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : '') } ``` ## 测试命令 ``` //本地开发全局包命令 运行这个命令, 将这个包安装到全局用于本地测试 npm link ```