In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to achieve the executable module in the front end of web". In the daily operation, I believe that many people have doubts about how to achieve the executable module in the front end of web. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to achieve the executable module in the front end of web". Next, please follow the editor to study!
Implement executable module
First, we need to create a project, which is called yncms-template-cli, and the project structure is as follows:
-commands / / this folder is used to place custom commands-utils-index.js / / Project entry-readme.md
To test, let's put something on index.js:
#! / usr/bin/env node / / the content above must be added to the file header to specify the running environment as node console.log ('hello cli')
For normal nodejs projects, we can just use node index.js, but this is scaffolding, which is definitely not allowed. We need to publish the project to npm, and the user can install it globally, and then we can directly use our custom commands, like yncms-template.
So, we need to make some changes to our project by first adding the following to packge.json:
"bin": {"yncms-template": "index.js"}
In this way, yncms-template can be defined as a command, but it can only be used in the project at this time, not as a global command. Here, we need to use npm link to link it to the global command. After successful execution, you can find the corresponding files in your global node_modules directory. Then enter the command to test it. If the following appears, the first step has been more than half successful:
PS E:\ WorkSpace\ yncms-template-cli > yncms-template hello cli
However, at present, this command can only be used on our own computers. If you want others to install it, you need to publish it to npm. The general process is as follows:
Sign up for a npm account. Those who already have an account can skip this step.
To log in using npm login, you need to enter username, password, email
Publish using npm public
This step is relatively simple, not to say much, but please note the following points:
If you use nrm, you need to switch the source to the NPM official source first.
There are several fields in package.json that need to be refined:
Name is the name of the published package and cannot be duplicated with the existing package of npm
Version is the version information. Each release must be higher than the online version.
Homepage, bugs and repository can also be added, corresponding to the following page
Add scaffolding introduction and usage to readme.md to facilitate others to use. If you need to add a logo to the document to show the number of downloads of scaffolding, you can generate it here.
After the release is successful, it will take a while to search for it in the npm repository.
Create command
Since it is scaffolding, we must not just let it output a paragraph of text, we also need to define some commands, users enter these commands and parameters on the command line, scaffolding will make the corresponding operation. There is no need for us to parse these input commands and parameters, there are ready-made wheels (commander) can be used, can fully meet our needs.
Help (--help)
After installing commander, we change the content in index.js to the following:
#! / usr/bin/env node const commander = require ('commander'); / / parse command line input using commander, which must be written at the end of all content commander.parse (process.argv)
At this point, although we do not define any commands, we have a help command defined within commander-help (abbreviated-h):
PS E:\ WorkSpace\ yncms-template-cli > yncms-template- h Usage: index [options] Options:-h,-- help output usage information
Version (--version)
Next, we create a query version of the command parameters, adding the following to index.js:
/ / check the version number commander.version (require ('. / package.json') .version)
In this way, we can check the version number on the command line:
PS E:\ WorkSpace\ yncms-template-cli > yncms-template- V 1.0.10 PS E:\ WorkSpace\ yncms-template-cli > yncms-template--version 1.0.10
The default parameter is uppercase V. if you need to change it to lowercase, make the following changes:
/ / check the version number commander .version (require ('. / package.json'). Version) .option ('- vGramage talk talk versionnumbers, 'check the version number'); PS E:\ WorkSpace\ yncms-template-cli > yncms-template- h Usage: index [version] Options:-V,-- version output the version number-h,-- help output usage information
Init subcommand
Next, let's define an init command, such as yncms-template init test.
Add the following to index.js:
Commander .command ('init') / / defines the init subcommand, which can be received in the function of action as a required parameter. If you need to set a non-required parameter, you can use brackets .option ('- d,-- dev', 'get development version') / / configuration parameter Used in shorthand and full writing, split .description ('create project') / / command description. Action (function (name, option) {/ / command executes the operation. The parameters correspond to the parameters set above / / all the actions we need to perform are completed here console.log (name) Console.log (option.dev);})
Now let's test it:
PS E:\ WorkSpace\ yncms-template-cli > yncms-template init test-d test true
For specific usage of commander, please check the official documentation for yourself.
In this way, even if a prototype of a custom command is complete, there are still a few things to do:
Implementing the specific actions performed by the init command will be described in a separate section below.
To facilitate maintenance, split the command action into the commands folder
Pull item
Above, we defined the init command, but did not achieve the goal of initializing the project, so let's implement it.
In general, project templates can be handled in two ways:
Putting the project template and this scaffolding together, the advantage is that after the user installs the scaffolding, the template is local and the initialization is faster; the disadvantage is that the project template is more troublesome to update because it is coupled with the scaffolding
Put the project into a separate GIT warehouse, the advantage is that the template update is relatively simple, because it is independent, you only need to maintain the template's own warehouse, and you can control the pull permission, because if it is a private project, then people without permission cannot pull successfully; the disadvantage is that you have to pull it from GIT every time it is initialized, which may be slower, but the impact is not great, so it is recommended to choose this way.
First, we use download-git-repo to encapsulate a clone method for pulling items from git.
/ / utils/clone.js const download = require ('download-git-repo'); const symbols = require (' log-symbols'); / / for output icon const ora = require ('ora'); / / for output loading const chalk = require (' chalk'); / / for changing text color module.exports = function (remote, name, option) {const downSpinner = ora ('downloading template'). Start () Return new Promise ((resolve, reject) = > {download (remote, name, option, err = > {if (err) {downSpinner.fail (); console.log (symbols.error, chalk.red (err)); reject (err); return;} DownSpinner.succeed (chalk.green ('template downloaded successfully!')) ; resolve ();}; / commands/init.js const shell = require ('shelljs'); const symbols = require (' log-symbols'); const clone = require ('.. / utils/clone.js'); const remote = 'https://gitee.com/letwrong/cli-demo.git'; let branch =' master'; const initAction = async (name, option) = > {/ / 0. Check whether the console can run `git `, if (! shell.which ('git')) {console.log (symbols.error,' sorry, the git command is not available!') ; shell.exit (1);} / 1. Verify that the input name is legal if (fs.existsSync (name)) {console.log (symbols.warning, `already exists project folder ${name}! `); return;} if (name.match (/ [^ A-Za-z0-9\ u4e00 -\ u9fa5characters -] / g) {console.log (symbols.error, 'illegal characters in the project name!') ; return;} / / 2. Get option and determine the template type (branch) if (option.dev) branch = 'develop'; / / 4. Download template await clone (`direct:$ {remote} # ${branch} `, name, {clone: true});}; module.exports = initAction
Test it, and you can pull the project successfully without accident.
The project pulled here is associated with the remote repository, and we need to delete it (since our project is managed by svn, delete the .git folder directly. If you use git, you can initialize it with git init) and clean up some redundant files:
/ / commands/init.js / / 5. Clean up files const deleteDir = ['.git', '.gitignore', 'README.md',' docs']; / / files to be cleaned const pwd = shell.pwd (); deleteDir.map (item = > shell.rm ('- rf', pwd + `/ ${name} / ${item}`))
Have a little personalization.
In the above process, we implemented the basic function of a scaffolding, which is roughly divided into three processes (pull template-> create project-> wrap-up), and also solved the first problem encountered in my project above. Next, let's take a look at how to solve the second problem.
The solution is to force the developer to enter the corresponding configuration through the command line when creating the project, and then write the configuration file automatically, which can effectively avoid the embarrassment of forgetting to fill in. Of course, in this way, we can also initialize the project dynamically according to the input of the user, so as to achieve the purpose of personalization.
Here we can directly use the ready-made wheel inquirer can be done, the effect is the same as VueCli to create a project, support many types, more powerful, but also relatively simple, specific usage can see the official documentation. Here I go directly to the code and add the following before step 4 (download the template):
/ / init.js const inquirer = require ('inquirer'); / / define the question to ask const questions = [{type:' input', message: 'please enter the template name:', name: 'name', validate (val) {if (! val) return' template name cannot be empty!' ; if (val.match (/ [^ A-Za-z0-9\ u4e00 -\ u9fa5template -] / g)) return 'template name contains illegal characters, please re-enter'; return true;}}, {type: 'input', message:' enter template keywords ( Split):', name: 'keywords'}, {type:' input', message: 'enter template introduction:', name: 'description'}, {type:' list', message: 'please select template type:', choices: ['responsive', 'desktop', 'mobile'] Name: 'type'}, {type:' list', message: 'please select template category:', choices: ['full site', 'single page', 'theme'], name: 'category'}, {type:' input', message: 'please enter template style:', name: 'style'} {type: 'input', message:' please enter template color:', name: 'color'}, {type:' input', message: 'please enter your name:', name: 'author'}] / / get the content entered by the user through inquirer const answers = await inquirer.prompt (questions); / / print the user's configuration to make sure it is correct console.log ('-'); console.log (answers); let confirm = await inquirer.prompt ([{type: 'confirm', message:' confirm creation?' , default: 'yearly, name:' isConfirm'}]); if (! confirm.isConfirm) return false
After getting the configuration entered by the user, you can write to the configuration file or do personalized processing, which is too easy, so I won't repeat it here.
And a flower to silk
At this point, a scaffolding that fully meets the needs is complete, but as an aspiring programmer, we can do something more about the interface and ease of use:
Add loding animation to asynchronous operations, you can use ora directly
Const installSpinner = ora ('installing dependency.') .start (); if (shell.exec ('npm install'). Code! = 0) {console.log (symbols.warning, chalk.yellow (' automatic installation failed, please install manually!')) ; installSpinner.fail (); / / installation failed shell.exit (1);} installSpinner.succeed (chalk.green ('dependent on installation success!'))
Give an icon prompt when the operation succeeds or fails, and use log-symbols
You can add some color to the text and use ready-made wheel Chalk in the same way.
When it takes a long time to install dependencies or other things, the user may cut the terminal to the background, and then we can use node-notifier to notify the user when the operation is completed.
Notifier.notify ({title: 'YNCMS-template-cli', icon: path.join (_ _ dirname,' coulson.png'), message: '♪ (^ ∀ ^ ●) Congratulations, successful creation of the project!' });
When creating a project, we may need to execute some shell commands, which can be done using shelljs, for example, we need to open vscode and exit the terminal after the project is created.
/ / 8. Open the editor if (shell.which ('code')) shell.exec (' code. /'); shell.exit (1); at this point, the study on "how to implement the executable module in the web front end" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.