Internal front-end tool platform construction

What’s this?

  • The scripting tools within the front end group are deposited in this place and can be easily shared and used by the team members
  • We want to be able to execute some simple commands like Linux commands, such as: FE xx, and then implement some functionality

What you want to achieve?

  • After NPM install -g eslint, the terminal enters eslint to execute the esLint validation script
  • We are performing FE xx and can execute our own scripts

Design how to use it first, then implement it later (FE stands for text-end)

  1. Install: NPM install -g@mycompany /fe
  2. Use:
    Fe or FE -h Viewing help FE-v Viewing version The platform tool is used. For example, terminal input: FE// The following is printedThe CLI scaffold pulls the internal template mock to switch to mock mode. Switch from Mock mode to API mode according to the API AndMock object API normal mode in fe.config.js. Use the API - PKG PKG mode of the apiAndMock object in fe.config.js: switch to API mode and put the return value of the response in the packet layer to simplify the output. /route/routes.js and the.vue file (./ SRC /components) of the route are generated automatically from the apiAndMock object route in fe.config.js. File-route listens to the directory (the components directory by default) based on the passed parameters, and automatically generates the./route/routes.js file when the file changes. Example: fe lan. / SRC /views [replace or r] [noOutput or n] getEn"Chinese": "English"into"English": "English", example: fe getEn SRC /langs/en.json -h, --help display helpforCommand terminal input: FE Mock executes the mock part of the script, switching to mock modeCopy the code

How do you build such a front-end tool platform?

Make an outline, and we’ll talk more about it later

  1. Manage code with internal GitLab (or github or Gitee if not available)
  2. Internal NPM domain is required (public network NPM will work if not available)
    • NPM install -g xx (NPM install -g xx) can be easily downloaded by other members of the team. Second, it can be easily managed
  3. Configuration package. Json
  4. Configuration entry file main.js
  5. Publish to an internal NPM domain
  6. Tests during script development?

1. Manage code on internal GitLab (github or Gitee if not available)

The basic Git operation, I believe everyone can, skip

2. Internal NPM domain is required (public network NPM is acceptable if not available)

Follow point 5 below (5. Publish to internal NPM domains)

3. The configuration package. Json

{
  "name": "@myCompany/fe"."version": "1.0.51"."description": "Front End Tool Platform"."scripts": {
    "dev": "node bin/main.js"."p": "node utils/publish.js && lnpm publish && npm i -g @myCompany/fe"
  },
  "author": "bigtree"."license": "ISC"."dependencies": {},"devDependencies": {},"bin": { // The bin field is the most important one
    "fe": "./bin/main.js" // Note that "./bin/main.js" refers to the main.js file in the directory (below the file directory structure)}}// The bin field is the most important one- To enable: terminal input: FE to print the XXX execution script, you need to configure bin// Refer to the package.json in esLint source code
    "bin": {
        "eslint": "./bin/eslint.js" // The key of the bin object can be resolved as a global environment variable, similar to node. It's actually triggered by node}, the directory structure of the file @mycompany -fe bin main.js.gitignore package.json package-lock.json readme.mdCopy the code
// The terminal executes the following: Fe is added to the node's global variable pool
xxx-MacBook-Pro / % npm i -g @myCompany/fe
xxx-MacBook-Pro / % where fe
/Users/xxx/.nvm/versions/node/v1221.. 0/bin/fe
xxx-MacBook-Pro bin % cd /Users/xxx/.nvm/versions/node/v1221.. 0/bin
xxx-MacBook-Pro bin % ls
fe           eslint         http-server       node          npm      
npx          stylelint
Copy the code

Install: NPM i-g@mycompany /fe (to be released, how to release in point 5 (5. Publish to an internal NPM domain)

The final terminal type: fe will execute @mycompany -fe/bin/main.js

4. Configure the entry file main.js

#! /usr/bin/env node
// The above is to configure the current environment variable address: MAC is fixed

/* File description: * Command entry file */

const commander = require('commander') // Let the command take effect, for example, fe-h
const Chalk = require('chalk')
const path = require('path')
const pkgJson = require('.. /package.json')
const { exec } = require('child_process') // Run commands such as node a.js
const autoRouteAndFile = require('./autoRouteAndFile/entry.js') // Other script files
const autoApiAndMock = require('./autoApiAndMock/entry.js') // Other script files
const autoFileRoute = require('./autoFileRoute/entry.js') // Other script files

// Define the version number and command options
commander
  .version(pkgJson.version, '-v -V --version') // If you do not write this, you can only use the uppercase -v
  .option('cli'.'Scaffold pulls internal formwork')
  .option('mock'.'Switch to mock. According to the apiAndMock object in fe.config.js')
  .option('api'.'Normal mode: Switch from Mock to API mode. According to the apiAndMock object in fe.config.js')
  .option('api-pkg'.'PKG mode: Switch to API mode and put the return value of the response in the packet layer to simplify the output. According to the apiAndMock object in fe.config.js')
  .option('route'./route/routes.js and the.vue file (in./ SRC /components) corresponding to the route are automatically generated based on the route object in fe.config.js, ')
  .option('file-route'.The./route/routes.js file is automatically generated when the file changes. (eg: fe file-route views) ')
  .option('lan'.Fe lan. / SRC /views [replace or r] [noOutput or n])
  .option('getEn'.'Convert "Chinese ": "English" to "English": "English", using fe getEn SRC /langs/en.json')
  .parse(process.argv) // let commander can get process.argv

// The absolute path of the configuration file (where the current command is executed)
const configPath = path.join(process.cwd(), 'fe.config.js')
console.log('Read configuration file path is:' + configPath)

// get ./fe.config.js
const getConfig = (key) = > {
  let Config = null
  try {
    Config = require(configPath)
  } catch (e) {
    console.log(Chalk.red('error: Fe.config.js must be configured to use this command '))
    console.error(Chalk.red(e))
  }
  if (Object.prototype.toString.call(Config) === '[object Object]') {
    if(! key) {return Config
    } else {
      if (Config[key]) {
        console.log(Chalk.green('Read configuration file successfully! '))
        return Config[key]
      } else {
        console.log(Chalk.red('Please configure fe.config.js inside${key}Configuration items `))}}}else {
    console.error(Chalk.red('Please configure fe.config.js correctly'))}}// main
const main = () = > {
  if (commander.args.length === 0) { // When input fe directly
    const realPath = path.join(__dirname, 'main.js')
    exec(`node ${realPath} -h`.(err, stdout, stderr) = > {
      if (err) console.error(Chalk.red(err))
      console.log('Welcome to the front end tool platform, use example: FE Mock \n${stdout}`)})}else { // When fe xx is entered
    const cmd = commander.args[0]
    if (['mock'.'api'.'api-pkg'].includes(cmd)) {
      autoApiAndMock(getConfig('apiAndMock'))}else if (cmd === 'route') {
      autoRouteAndFile(getConfig('route'))}else if (cmd === 'file-route') {
      autoFileRoute(getConfig('fileRoute'))}else if (cmd === 'lan') {
      require('./lan/lan-script.js')
      console.log('do something... ')}else if (cmd === 'getEn') {
      require('./lan/getIndia.js')
    }
  }
}

main()
Copy the code

5. Publish to the internal NPM domain

Open the console and enter the following commands

  • If you are sending a package for the first time, use NPM adduser
  • If not for the first time, use NPM login

Next, enter the account name, password, email

username:xxx
password:
Email:[email protected] 
Copy the code

The directory at the root of the project, at the same level as package.json

  • Enter NPM Publish

You can then find your newly released packages in the internal NPM domain or the public NPM domain

6. Testing during script development?

  1. Small script

    • You can copy files directly to the test project, directly test
    • Note: If the path is manually copied, it may not be correct to write a relative path. Use path.resolve() to resolve an absolute path
  2. Generic method (no manual copy, just inside the source)

    1. NPM link: docs.npmjs.com/cli/v7/comm…
    2. Use the editor to get the absolute path of main.js, and then execute directly

    For example: / Users/XXX/Desktop/project/XXX/bin/main js (effect and fe)

To use the debugger:

In the root directory of the current project, type node — inspec-brk bin/main.js to start debugging mode