Building a minimal implementation scaffolding with Node

山头人汉波
中文

foreword

This article introduces the use of Node as a scaffold to facilitate the rapid development of projects. We develop scaffolding, not projects. At present, I only have one scaffolding - Koa scaffolding . When I write about React and webpack later, I will build my own set of H5-side development templates. This article starts from the realization of minimum scaffolding, and will add bricks and tiles on this basis in the future.

Introduction

A: Brother B, what can Node do?

B: Build a web service

A: Not only that, it can also operate the system

B: How to say?

A: Do you know Webpack? It's written in Node. Others like create-react-app , vue-cli , @tarojs/cli are all written in Node, these cli are called scaffolding, you can download templates for rapid development with just a few commands

B: (After all kinds of envy and praise), I also want to make my own scaffolding

A: I will teach you

A scaffolding idea

Looking at the respective repositories of create-react-app , vue-cli , and @tarojs/cli , we can draw some commonalities, such as multiple sets of templates, friendly interaction, beautiful UI, and so on. Here we take taro as an example, use it first, take a look, and then imitate it

使用Taro-cli创建项目

How does it choose different templates to generate different files? Obviously there is only one basic template. Select scss to generate scss files, and select TypeScript to generate TS files. I still don’t understand the source code. I will take a look after writing webpack. We will only do the simplest scaffolding first.

Create project

 mkdir azhu-cli
cd azhu-cli
npm init -y

Then write some project information in package.json

npm packages that need to be installed

Let's make a table first to see what each npm package is and what it is useful for, and then add it step by step when writing code

package name illustrate
commander execute complex commands
inquirer Q&A interaction
download-git-repo Download remote template
chalk Let the words you console.log come out with colors, such as green words when successful
ora loading

create a command

First create index.js and write in the code

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

Run the node program in the terminal and enter the node command

 node index.js

Can output hello world correctly, the code at the top of the code #!/usr/bin/env node tells the terminal that this file should be executed using node

Generally cli has a specific command, such as taro , git etc. We set our command azhu . How can I make the terminal recognize this command? Very simple, add a field bin to the package.json file, and declare a command keyword and the corresponding execution file:

 # package.json
...
"bin": {
    "azhu": "index.js"
}
...

Then we test it, enter azhu in the terminal, it will prompt:

azhu错误

Why is this so? Usually when we use the cli tool, we need to install it first, such as vue-cli, @tarojs/cli, which needs to be installed globally before use:

 npm i vue-cli -g
npm i @tarojs/cli -g 

And our azhu-cli has not been published on npm, and of course it has not been installed, so the terminal does not recognize this command yet. Usually we want to test an npm package locally, we can use the command npm link to install this package locally, let's execute it:

 npm link

Execute the azhu command again, and you will see hello world

Note: npm unlink uninstalls local packages

execute complex commands

commander: handles command line interactions

  • Comes with -V, -h interaction
  • Interactions can be added via program.command
  • program.parse the command parameters into the commander pipeline, usually in the last execution
 npm i commander --save

Retrofit index.js

 #!/usr/bin/env node

const program = require('commander')
const package = require('./package.json')
program.version(package.version)
program.parse(process.argv)

run azhu -h

commander处理

Add Q&A action

inquirer add Q&A action

 npm i inquirer --save

The syntax is very simple, just look at the code directly:

 inquirer
  .prompt([
    { type: 'input', message: '请输入项目名称', name: 'name' },
    {
      type: 'list',
      message: '请选择项目模板',
      name: 'template',
      choices: ['koa-basic'],
    },
  ])
  .then((answers) => {
    console.log('answers', answers)
  })

The name in each option is the value of the answer output

inquirer

clone template

download-git-repo

  • Download remote template
 npm i download-git-repo --save

Originally used shelljs, but I couldn't download it, so I could only choose another tool

When we download and write the project name and select the template, the next step is to download the template from the remote warehouse

 .then((answers) => {
      console.log('正在拷贝项目,请稍等')
      const remote = 'https://github.com:johanazhu/koa-basic#master'
      const tarName = answers.name
      download(remote, tarName, { clone: true }, function (err) {
        if (err) {
          console.log(err)
        } else {
          console.log('成功')
        }
      })
    })

Add UI interaction

Sometimes it takes a lot of time to download the remote warehouse. We must add some UI effects to optimize the experience for the experience.

chalk & ora

 npm i chalk ora --save

chalk is to add color to the console

ora adds loading effect

 ...
.then((answers) => {
    console.log('正在拷贝项目,请稍等')
    const remote = 'https://github.com:johanazhu/koa-basic#master'
    const tarName = answers.name
    + const spinner = ora('download template......').start()
    download(remote, tarName, { clone: true }, function (err) {
        if (err) {
            + console.log(chalk.red(err))
            spinner.fail()
        } else {
            + console.log(chalk.green('成功'))
            spinner.succeed()
        }
    })
})

The effect is as follows:

chalk&ora

publish npm

Log in to npm first, then publish

 npm login...npm publish

Additional knowledge points

package management

包管理方式对比

monorepo

  • Software development strategy for storing multiple project code in one repository
  • Put all project related in one repository (like React, Babel, Umi, Taro)
  • Centralized management
  • Advantage

    • Unified Workflow
    • Reduce infrastructure costs
    • Improve team collaboration efficiency
  • disadvantage

    • volume problem
    • Permissions issue
    • version control

multirepo

  • Put in multiple repositories by module (webpack, rollup)
  • Advantage

    • flexible
    • Safety
  • disadvantage

    • code reuse
    • Version management
    • Development and debugging
    • Build the infrastructure

Large projects can use monorepo, and those with strong independence can use multirepo

I personally prefer the philosophy of multirepo

Some people have risen to the philosophical level. In fact, I think different projects should adopt their own management methods, such as webpack, rollup, etc., the project independence is relatively strong, you can use multirepo, and frameworks such as React, Umi, Taro, etc. , it first needs to split the function points, and secondly, each sub-library needs to depend on the main library. If the multirepo method is used, it will be very troublesome to associate, and the unified management method can save a lot of time

common problem

One: Use shelljs are often errors and cannot be solved temporarily, so use download-git-repo this way

 fatal: unable to access 'https://github.com/johanazhu/koa-basic/': OpenSSL SSL_read: Connection was reset, errno 10054

solution

Open the Git command page and execute the git command script: modify settings, release ssl verification

 git config --global http.sslVerify "false"
Note: git config --list to view your config information

Two: download-git-repo error report

 'git clone' failed with status 128

Solution: https://github.com/wuqiong7/Note/issues/17

I changed the remote address to: https://github.com:johanazhu/koa-basic#master just fine

Github released: https://github.com/johanazhu/azhu-cli

References

阅读 433
138 声望
473 粉丝
0 条评论
138 声望
473 粉丝
文章目录
宣传栏