This is the first day of my participation in the First Challenge 2022
Everybody is good! I am small du Du, is a touch fish front-end engineer, today talk about front-end engineering, and explain how to spend ten minutes to create a dedicated to their own CLI, I hope we can discuss a lot of messages, together to discuss the next front-end engineering, what high method message pointed out ~
preface
As a developer, what is NPM compared to NPM? NPM is simply a package management tool for Node.js.
Actually, I saw one of the cool ones a long time ago. It’s called Taro
Taro taro has become an ambassador for us. We visit taro taro in The first place. If you see li Bai coming into a wine store, you will see Du Fu going up a mountain
5 minutes Create your own command
Create an NPM account and log in
First of all, we need to register an account on the NPM website, and then log in from the command line
npm login
npm notice Log in on https://registry.npmjs.org/
Username: ...
PassWord: ...
Email: ...
Copy the code
Here we should pay attention to two points in particular:
- The address must be registry.npmjs.org/, not HTTP
- The node version is 7.0.0 or later because TLS 1.2 or later is not currently supported
Initialize a project
This is when we need to create a package, such as domesy-CLI, search the NPM website first to see if the package is registered, if not, congratulations, you can use the package name
Next create a domesy-CLI folder and execute NPM init in this project which will create a package.json folder and then we need to use bin
{
"name": "domesy-cli"."version": "0.0.1"."description": "Order domesy"."main": "index.js"."bin": {
"domesy": "bin/domesy.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "domesy"."license": "ISC"
}
Copy the code
Bin /domesy.js is the file directory in my name
release
Then we do NPM publish
Let’s check it out on the NPM website
Note:
- If we want to update again, we need toChange the version in package.jsonIn order to use
npm publish
- If you want to delete it, use NPM unpublish -f package name
use
NPM install -g domesy-cli is used to download the NPM install -g domesy-cli command is also available in the bin
Note: currently you can use the domesy command but no specific operations are written so it has no effect, the following are some basic operations
Create your own CLI
Having created our own synonym of domesy through the 4 steps above, let’s go straight to domesy and see how to create an exclusive CLI.
Let me first make a list of what THE CLI looks like after I finish it, so that it can be more convenient to explain.
A simple analysis of the functions:
- The first and second are to download my two projects, one is PC terminal, the other is mobile terminal, if you are interested in it, you can use it
cli
Download and have a look (in addition, you can have a look at the document at the end of the article, which describes how to configure your own project, and support 😎) - The third and fourth are mainly
Install dependencies
andTo run the program
Operation, may be a little chicken ribs, do not spray oh ~ - The fifth is to check the version number of the current package
- The sixth is to exit purely, convenient user exits directly, is not very intimate 😁
Install dependencies
In my first post: Building the React Mobile framework out of the box, I explained a gadget
Type a big ‘DOMESY ‘when packing! ‘As their own “logo”, beside the topic, directly introduce the need to install plug-ins ~
- The clear: clear screen
- Chalk: Decorative, adding color to the output on the terminal
- Figlet: The function is to convert letters into pictures to make them more eye-catching
- Git-pull-or-clone: Download the code
- Inquirer: Type interactive commands on the command line
There are only five plug-ins.
DOMESY big logo!
When we want to draw a large logo, we need to use chalk and Figlet. Without further ado, we can go directly to the code:
// lib/api.js
const chalk = require("chalk");
module.exports.log = (msg, color='green'. arg) = > console.log(chalk[color](msg, arg));
// bin/domesy.js
const figlet = promisify(require("figlet"));
const clear = require("clear");
clear(); // It would be better to empty the console during execution
log(
figlet.textSync("DOMESY !", {
horizontalLayout: "Isometric1".verticalLayout: "default".width: 80.whitespaceBreak: true,}).'blue'
)
Copy the code
Download the project
Download the process required by the project
- The first thing you need to do is specify a folder to download the project, so use it here
inquirer
Let’s do a simple interaction, tell the user what I want to download - The second is through
git-pull-or-clone
To handle the download location (I synchronized the project to Gitee because git is old) - Then we print it out and tell the user it’s downloading
module.exports = async() = > {console.log("path", resolve("."));
// Project name
const name = await inquirer.prompt([{
type: 'input'.message: 'Set file name 😎😎😎'.name: 'name'.default: "react-mobile" / / the default value
}])
const repo = 'https://gitee.com/domesy/react-mobile.git'
const desc = resolve(`. /${name.name}`);
console.log("desc", desc);
const process = ora('🚗🚗🚗 download.....${repo}`);
process.start();
try {
await download(repo, desc);
process.succeed();
log('🚗🚗🚗 Download completed');
} catch (e) {
console.log(e); process.fail(); }};Copy the code
To achieve this effect
Install dependencies
After downloading, the dependency must be installed first, so we need to use the child_process module and wrap it so that we can operate directly without entering the file
// Encapsulate spawn lib/api.js
module.exports.spawn = async(... args) => {const { spawn } = require('child_process');
return new Promise(resolve= > {
constproc = spawn(... args) proc.stdout.pipe(process.stdout) proc.stderr.pipe(process.stderr) proc.on('close'.() = > {
resolve()
})
})
}
Copy the code
All we need to do is go to this folder and execute YARN Install
log('🚴🏻🚴🏻 port x please wait for 🚴 ')
await spawn("yarn"['install'] and {cwd: `${name.name}/ `})
log('🚴🏻🚴🏻 🏻 🏻 install complete ')
Copy the code
In the meantime, you can use the fs.existsSync command to check if node_module is installed to make your CLI a little more perfect
Now let’s look at installing dependencies:
I want you to drag the project directly to the console and then execute it, but the dragged file will have Spaces and will not be able to install, so I need to use trim() to remove the Spaces
Start the project
Start the project in the same way as install dependencies except with different commands: await spawn(” YARN “, [‘run’, ‘start’], {CWD: desc})
Then we can use these to perfect our OWN CLI.
discuss
Now that you’ve completed the basic operations of the CLI, some might say that the front end is all bells and bods, but it’s not. I said one word at the beginning of this article: Front-end engineering
This word, to tell the truth not close to say far not far, in fact, in most companies, just to make the project, will not tube you, and even regardless of the code specification, as long as the product will need to make it, this is beside the point, not bs 😄
I want to ask you how do you deal with common components, when different projects use common components?
I started by manually copying components directly into another project, which is the easiest and lowest option, and obviously not applicable in large development where multiple people collaborate.
The git submodule command is also used to configure common components
However, I think git submodule is always too troublesome, so I asked the big guys how to deal with it. They use the same method as downloading a package, directly through NPM (only changed to the internal network), this way really feels quite high and convenient, so I came up with this article to sum up. O ha ha ~ O (studying studying)
If I were the leader of the front end, I would definitely use this way to manage the project, which is fantastic 😎😎😎
Do you have a better way to do this? Feel free to discuss it in the comments section below
extension
In the above explanation, I only talked about the most basic, in fact, the cli real function is more than this, you should know that umi commands can directly create a folder, and to link to the route
Also, in a traditional project, the project is very large, how can we separate the project and create a separate module through cli, so as to carry out better development, these functions can be realized through CLI, don’t you suddenly feel much higher, ha ha ha ~
What function, we can say, I will go to research, get rid of the word low ~
In addition, the code address is attached for everyone to visit. If it is helpful, please give a small Star for your support
Git address: domesy- CLI
Other good posts:
- Build the React mobile framework out of the box
- Build your Own Ant Design Pro V5
- Some common Dom operations that can be easily obtained with a single Hook?