preface
I had to maintain a very old project at work. It’s a long story. There are so many things I need to manually add when adding new modules to a project. Hopefully, by writing a node command, I can configure the things I need to configure in one click, such as: routes, controllers, less files, etc. In the end I just needed to write our cute module code in the generated template index.jsx.
How do I create the Node command?
$ mkdir my-plugin
$ cd my-plugin
$ npm init --yes
Copy the code
The script command to configure 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 "}}Copy the code
Create script JS
#! /usr/bin/env node console.log('hello word');Copy the code
Global Install Node command
npm install . -g
Copy the code
That’s how you create the Node directive. Here’s how to script the generated code.
The use of the inquirer
List the attributes you use and learn more about them.
1.input
Const promptList = [{type: 'input', message: 'Set a user name: ', name: 'name', default: "test_user" // default},{type: 'input', message: 'Please input phone number :', name: 'phone', validate: Function (val) {if(val. Match (/\d{11}/g)) {return val;} return "please enter 11 digits ";}}]; inquirer.prompt(promptList).then(answers => {});Copy the code
Effect:
2.list
Const promptList = [{type: "list", message: "author iscool :", name: "iscool", choices: [' cool ',' general cool '],}, {type: "List "," message ", name: "client", choices: Function (answers){return answers.iscool === 'NSTR'}, filter: function(val) {}},]; inquirer.prompt(promptList).then(answers => {});Copy the code
When is used to mark when this query appears!!!!
Write scripts to add templates
The author will add the following template:
For example, add index.jsx and index.module.less to the page folder:
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); }); })}); }Copy the code
First add the Module folder under the Page folder and use HTTP to pull down the index.jsx template from the line below the module folder you created.
conclusion
In general, doing the configuration required to create a new module through a Node directive doesn’t necessarily save much time, but it’s pretty cool, right?