Build an interactive front-end build environment (1)

The current front-end projects are so complex that they all need to rely on some build tools, the mainstream ones are webpack, gulp, gruntetc. Adding a variety of configuration files will form a relatively complex build environment. In general, we can write the parameters needed to build the project in the configuration file, but what if some of them need to be dynamically configured? Let's say we expressuse to start a local server, this needs to be allocated a port right? It is possible to write a port such as 8080 in the configuration file, but what if the port is occupied? Do we need to drop the process occupying our port kill, or modify the configuration file, and rundo it again? If all the parameters are written in the configuration file, once the build script is started, it is like a horse that is uncontrollable and will keep running. Then we can change our thinking. Can we make an interactive script, that is, after starting the build script, we can also intervene to modify some configurations. For example, if the port is occupied, we can enter a new port in the console, and then Continue to run the project, will it be more friendly?
The front-end construction environment is generally Nodescript-based. Fortunately, there is inquirea , which can easily interact with the console. As for how to use this library, I won't say it here. You can go to the official website to see its documentation. In addition, we also need to check in advance whether the port is occupied, and we can use a third-party library portscanner. Let's go directly to a demo, and implement the build script to allocate server ports at runtime:

const inquirer = require('inquirer');
const portscanner = require('portscanner');

const questions = [];
questions.push({
  type: 'input',
  name: 'port',
  default: 3000, // 默认端口是3000
  message: `请输入调试端口号`,
  validate(input) {
    const port = Number(input);
    return new Promise((resolve, reject) => {
      if (isNaN(port)) {
        reject('端口号必须为数字');
      } else {

       // 检查端口是否被占用了,如果被占用则重新输入
        portscanner.checkPortStatus(
          port,
          '127.0.0.1',
          (error, status) => {
            if (error) {
              reject(error);
            } else if (status === 'open') {
              reject(`${port} 端口号已经被占用`);
            } else {
              resolve(true);
            }
          }
        );
      }
    });
  }
});

inquirer
.prompt(questions)
.then(answer => {
  console.log(answer);
}).catch(console.log);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324958862&siteId=291194637