您的位置:首页 > Web前端 > Node.js

用Node写一条配置环境的指令

2020-02-13 12:15 771 查看

前言

工作中需要维护一个极老的项目,说来话长。在平时当需要往项目里添加新的模块时,我需要手动添加的东西太多了。由此希望通过编写一条node命令,可以让我一键完成配置我需要配置的东西,比如:路由,控制器,less文件等。最后我只需要在生成的模板index.jsx中写我们可爱的模块代码就行了。

如何创建Node命令?

$ mkdir my-plugin
$ cd my-plugin
$ npm init --yes

配置package的脚本命令

{ "name": "12", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {  "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "bin": {  "autocode": "bin/wflow.js" }, "dependencies": {  "inquirer": "^7.0.0" }}

创建脚本js

#!/usr/bin/env node
console.log('hello word');

全局安装node命令

npm install . -g

以上就是创建node指令的方法,下面介绍如何编写生成代码脚本。

inquirer的使用

列举用到的属性,更多用法请自行学习。

1.input

const promptList = [{
type: 'input',
message: '设置一个用户名:',
name: 'name',
default: "test_user" // 默认值
},{
type: 'input',
message: '请输入手机号:',
name: 'phone',
validate: function(val) {
if(val.match(/\d{11}/g)) { // 校验位数
return val;
}
return "请输入11位数字";
}
}];

inquirer.prompt(promptList).then(answers => {});

效果:

2.list

const promptList = [ {  type: "list",  message: "作者帅吗:",  name: "iscool",  choices: ['帅','一般帅'], }, { type: "list", message: "帅得什么级别:", name: "client", choices: ['吴彦祖','彭于晏'], when:function(answers){  return answers.iscool === '帅' }, filter: function(val) { }},];
inquirer.prompt(promptList).then(answers => {});

when用于标记此条询问何时出现!!!!

编写脚本添加模版

笔者要添加模版为以下:

以在page文件夹下添加index.jsx和index.module.less为例子:

function action(module_name, module_title) {
let url = 'https://raw.githubusercontent.com/justworkhard/Daily-Blog/master/2019-11/12/file/temp.jsx' fs.mkdir("app/page/" + module_name, () => {  fs.writeFileSync("app/page/" + module_name + "/index.module.less", "");  https.get(url,(res)=>{   res.setEncoding('utf8');    let rawData = '';    res.on('data', (chunk) => {    rawData += chunk;   });   res.on('end', () => {    fs.writeFileSync("app/page/" + module_name + "/index.jsx", rawData);   });  }) });
}

先是在page文件夹下面添加module的文件夹,使用http将线上的index.jsx模版拉下来放到创建的module文件夹下面。

结语

总的来说,通过一条node指令完成了新建模块所需的配置并不一定能节省多少时间,但却非常酷,不是吗?

链接:https://github.com/justworkhard/autocode.git

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Node 配置环境 指令