This article tries to make sense of something that seems complicated. Before we talk, we should always remember one sentence: all front-end concepts are paper tigers.
Scaffolding is a tool we use a lot, and it’s an important way to improve team performance. So a systematic grasp of scaffolding related knowledge, for front-end developers is very important, even if many people will not necessarily participate in their departments or companies in the future infrastructure work, but a systematic grasp of this skill can also facilitate our later source code reading. Let’s take a look at it.
1. Pre-knowledge
Before setting up our scaffolding, there are some common libraries that we need to take a quick look at. Of course, the knowledge of Node is also the most basic, if you do not understand the writing of node, you can start from the node API documentation and then look at this tutorial. Here listed in the development of scaffolding commonly used tool library, here will not be introduced, we can understand.
The name of the | Introduction to the |
---|---|
commander | Command line custom command |
inquirer | The cli asks the user questions and records the answers |
chalk | Console output content styling |
ora | Console Loading style |
download-git-repo | Download the remote template |
fs-extra | System FS module extension, provides more convenient API, and inherited the FS module API |
cross-spawn | Supports cross-platform invocation of system commands |
figlet | Logo Printing on the console |
Let’s give the scaffold a name, memo-CLI, for now. In the first phase, we will implement a simple scaffold tool for you to get started. Therefore, the basic functions need to be implemented:
- Run the memo-cli create command to start the project
- Ask the user to select the template to download
- Remotely pull a template file
We’ll start implementing these features step by step
2. Scaffolding construction steps 🏗
First we create an empty folder, then initialize our project and create a new entry file
$mkdir memo-cli $CD memo-cli $NPM init # $mkdir memo-cli $CD memo-cli $NPM init #Copy the code
Specify the entry file in package.json as cli.js 👇
{... "Bin" : {" memo - cli ":". / lib/cli. Js ". / / manually add the entry documents for cli js}}Copy the code
The NPM link links globally so that the memo-CLI command can be used locally
$ npm link
Copy the code
And that’s what we ended up with
├─ ├─ ├─ download.jsonCopy the code
2.1 Create scaffold start command
The first thing we need to figure out is what are we going to do? To implement this requirement, use the COMMANDER dependency. See vue-CLI for a common command like create. If the created project exists, you need to prompt whether to overwrite it.
- Install dependencies
$ npm install commander –save
- Create a command and open cli.js to edit it
#! /usr/bin/env node const program = require('commander') const packageJson = require(".. /package.json") program .version(packageJson.version) .command("create <app-name>") .description("create a new project") .option("--f, --force", "Overwrite target directory if it exist") Action ((name, options) => {console.log(name, options)}) // Get the command line argument program.parse(process.argv).Copy the code
Type memo-cli on the command line to check if the command is created successfullyWe can also validate our commandsmemo-cli create my-app
, will print in the consolemy-app
The command line input information 👍 is obtained successfully
2.2 Running Commands
Create the lib folder and create create.js under the folder
// lib/create. Js module.exports = async function (name, options) {console. Log ('>>> create. options) }Copy the code
Use create.js in cli.js
// bin/cli.js ...... program ...... .action((name, options) => {// perform the creation task in create.js require('./create.js')(name, options)})......Copy the code
Run the memo-cli create my-project, at this time, create. Js normally prints our entry and exit information
When creating a directory, you need to ask: Does the directory already exist?
- If there is
If {force: true} is used, the original directory is removed. If {force: false} is used, the user is asked whether to overwrite the directory
- If no, create one directly
Here is the fs extension tool Fs-extra
$ npm install fs-extra –save
Let’s next refine the implementation logic inside create.js
// lib/create.js module.exports = async function (name, options) {const CWD = process.cwd(); // lib/create.js module.exports = async function (name, options) {const CWD = process.cwd(); Const targetAir = path.join(CWD, name) // Does the directory already exist? If (fs.existssync (targetAir)) {// Is this mandatory? If (options.force) {await fs.remove(targetAir)} else {// TODO: Ask user if they are sure to override}}}Copy the code
At this point, we can determine whether there are duplicate folders in the current directory. If there are, we will remove them directly. Next we need to ask the user if they want to overwrite the existing folder.
2.3 Asking Questions Obtain the required information
Here we call on our old friend Inquirer to help us solve the command line interaction problem.
- One legacy: Ask the user whether to overwrite an existing directory
- User selection template
- User selected version
- Get a link to download the template
The first choice is to install the Inquirer
$ npm install inquirer –save
The user is then asked whether to Overwrite
See Create for the code for create
You can test yourself, for example, manually create a my-app project under the project folder, and then use scaffolding to create a new projectmemo-cli create my-app
The following command appears on the command line:
2.4 Obtaining Template Information
We create an http.js in the lib directory that handles fetching template and version information, and use Axios to fetch the github template.
For template code: (HTTP) [git.xiaojukeji.com/kledwu/memo…].
2.5 Users select templates
Once we have the template information, we create a generator.js specifically to handle the project creation logic and refer to the Generator for the code
Let’s test it out and see what it looks like, okay
2.6 Downloading a Remote Template
Download the remote template using the Download-Git-repo toolkit, which is actually on the tools menu listed above, but one thing to note when using it is that it does not support Promises. So we need to promise it using the promisify method in the Util module
$ npm install download-git-repo –save
Download the remote template code address Generator
Complete this and a simple scaffold is complete ✅
To see how this works, run the memo-cli create my-project
At this point, we can see that the template has been created 👏👏👏
Refer to the GitLab repository link for code
The first stage is just a simple introduction of how scaffolding responds to user input and the use of some common libraries, which is very helpful in the second stage. We will share some more in-depth content based on this and combined with Webpack later. For example, how does the scaffolding package the project and customize some of the scaffolding commands like memo-CLI build