通过package.json将视觉样式应用于npm脚本中使用的echo命令 [英] Apply visual styling to echo commands used in npm scripts via package.json

查看:60
本文介绍了通过package.json将视觉样式应用于npm脚本中使用的echo命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近已将具有npmpackage.json脚本的构建工具组合在一起,并且我有一些echo命令来说明当前正在运行的管道的哪些部分.

例如(来自我的package.json):

 {
    "scripts": {
        "clean": "rimraf a-directory/",
        "preclean": "echo \"\n[ Cleaning build directories ]\n\""
    }
}
 

当我执行Bash:npm run clean时,它会打印我的echo消息,然后清除相应的目录.

我想更改颜色,字体粗细,背景文本颜色,以使这些echo语句脱颖而出,一目了然,但一目了然,但我一直在努力寻找可以让我脱颖而出的起点能够做到这一点.

有很多有关通过gruntgulp或JS脚本在常规CLI/Bash脚本中执行此操作的信息,但我发现没有发现要从package.json的脚本部分进行尝试. /p>

我想念什么?感谢所有帮助.

非常感谢.

解决方案

控制台/终端通常为 ANSI提供支持/VT100控制顺序,因此可以使用这些代码控制字体颜色,字体粗细,背景颜色等.

  • 有关仅限Bash的解决方案,请参阅下面的 Bash(MacOS/Linux/等.)部分.

  • 但是,如果需要跨平台支持,请遵循以下跨平台部分中所述的解决方案.


Bash(MacOS/Linux/等.)

重要说明:以下内容在非bash控制台上无法成功运行,例如 Windows命令提示符(即cmd.exe)或 PowerShell .

下面的示例npm脚本:

 "scripts": {
  "clean": "rimraf a-directory/",
  "preclean": "echo \"\\x1b[104m\\x1b[97m\n[ Cleaning build directories ]\n\\x1b[0m\""
}
 

...在运行npm run clean时(即带有蓝色背景的白色文本)将在控制台中记录如下内容:

必要的语法/代码的分解:

             <Esc> characters
   ┌─────────┬────┴─────────┐
   │         │              │
 ┌─┴─┐     ┌─┴─┐          ┌─┴─┐
 \\x1b[104m\\x1b[97m Mssg \\x1b[0m
      └─┬─┘     └─┬┘└─┬─┘      └┬┘
        │         │   │         │
        │         │   │         │
        │         │   │         │
        │         │   │  Reset all attributes
        │         │   │
        │         │  Your Message
        │         │
        │       White Text
        │       
 Light blue background
 

更多示例:

以下示例npm-scripts提供了更多示例:

 "scripts": {
  "a": "echo \"\\x1b[1m\\x1b[39mBold Text\\x1b[0m\"",
  "b": "echo \"\\x1b[91mLight Red Text\\x1b[0m\"",
  "c": "echo \"\\x1b[94mLight Blue Text\\x1b[0m\"",
  "d": "echo \"\\x1b[92mLight Green Text\\x1b[0m\"",
  "e": "echo \"\\x1b[4m\\x1b[91mLight Red Underlined Text\\x1b[0m\"",
  "f": "echo \"\\x1b[101m\\x1b[97mLight Red Background and White Text\\x1b[0m\"",
  "g": "echo \"\\x1b[104m\\x1b[97mLight Blue Background and White Text\\x1b[0m\"",
  "h": "echo \"\\x1b[30m\\x1b[103mLight Yellow Background and Black Text\\x1b[0m\"",
  "i": "echo \"\\x1b[97m\\x1b[100mDark Gray Background and White Text\\x1b[0m\"",
  "bash-echo-all": "npm run a -s && npm run b -s && npm run c -s && npm run d -s && npm run e -s && npm run f -s && npm run g -s && npm run h -s && npm run i -s"
},
 

使用上述脚本运行npm run bash-echo-all -s会将以下内容输出到您的控制台(-s选项只会使npm日志少一些):

可以在本文顶部的链接中找到更全面的代码列表(或查看下面的跨平台部分中列出的代码),但请记住,并非所有的ANSI/VT100控件支持序列.


跨平台

对于跨平台解决方案,(该解决方案可成功与 Bash Windows命令提示符/cmd.exe PowerShell 等一起使用. ..),则需要创建一个nodejs实用程序脚本来处理日志记录.然后可以通过您的npm-scripts调用此nodejs脚本.

以下步骤描述了如何实现:

  1. 创建一个nodejs实用程序脚本,如下所示:

    echo.js

     const args = process.argv;    
    const mssg = args[2];
    
    const opts = [
      '-s', '--set',
      '-b', '--bg-color',
      '-f', '--font-color'];
    
    function excapeAnsiCode(code) {
      return '\x1b[' + code + 'm';
    }
    
    const ansiStyles = opts.map(function (opt) {
      return args.indexOf(opt) > -1
          ? excapeAnsiCode(args[args.indexOf(opt) +1])
          : '';
    });
    
    console.log('%s%s%s', ansiStyles.join(''), mssg, '\x1b[0m');
     

    将文件命名为echo.js,并将其保存在项目目录的根目录中,即保存在package.json所在的文件夹中.

  2. 然后,以您的示例为例,如下所示将npm-script添加到package.json:

     "scripts": {
      "clean": "rimraf a-directory/",
      "preclean": "node echo \"[ Cleaning build directories ]\" --bg-color 104 --font-color 97"
    }
     

    运行npm run clean时,使用仅使用 bash 的解决方案时,您会看到与以前相同的消息记录到控制台,即带有蓝色背景的白色文本.

通过npm-scripts

调用echo.js的用法语法概述

 node echo \"message\" [[-s|--set] number] [[-b|--bg-color] number] [[-f|--font-color] number]
 

  1. node echo \"message\"

    node echo \"message\"部分是必需的. message是您输入要记录的消息的地方,必须 括在转义的双引号\"...\"中,以防止拆分.

    用于格式化/样式设置的其余部分都是可选的,可以按任何顺序定义.但是,使用时,它们必须在开始的node echo \"message\"部分之后进行,并用单个空格分隔.

  2. []

    --set选项,或者它的速记等效项-s,后跟一个空格,并且以下ANSI代码之一可用于指定常规格式:

     ┌─────────────────────────┐
    │ Code  Description       │
    ├─────────────────────────┤
    │  1    Bold/Bright       │
    │  2    Dim               │
    │  4    Underlined        │
    │  5    Blink             │
    │  7    Reverse/invert    │
    │  8    Hidden            │
    └─────────────────────────┘
     

    注意:代码14 Bash 一起成功使用,但是 Windows命令提示符 Powershell .因此,如果跨平台的可重复性很重要,我建议您完全避免使用--set | -s选项.

  3. [--bg-color|-b]

    --bg-color选项,或者它是速记等效的-b,后跟一个空格,并且以下ANSI代码之一可用于指定背景颜色:

     ┌─────────────────────────┐
    │ Code  Background Color  │
    ├─────────────────────────┤
    │  49   Default           │
    │  40   Black             │
    │  41   Red               │
    │  42   Green             │
    │  43   Yellow            │
    │  44   Blue              │
    │  45   Magenta           │
    │  46   Cyan              │
    │  47   Light Gray        │
    │  100  Dark Gray         │
    │  101  Light Red         │
    │  102  Light Green       │
    │  103  Light Yellow      │
    │  104  Light Blue        │
    │  105  Light Magenta     │
    │  106  Light Cyan        │
    │  107  White Cyan        │
    └─────────────────────────┘
     

  4. [--font-color|-f]

    --font-color选项,或等同于速记的-f,后接一个空格,并且以下ANSI代码之一可用于指定字体颜色:

     ┌─────────────────────────┐
    │ Code  Font Color        │
    ├─────────────────────────┤
    │  39   Default           │
    │  30   Black             │
    │  31   Red               │
    │  32   Green             │
    │  33   Yellow            │
    │  34   Blue              │
    │  35   Magenta           │
    │  36   Cyan              │
    │  37   Light Gray        │
    │  90   Dark Gray         │
    │  91   Light Red         │
    │  92   Light Green       │
    │  93   Light Yellow      │
    │  94   Light Blue        │
    │  95   Light Magenta     │
    │  96   Light Cyan        │
    │  97   White Cyan        │
    └─────────────────────────┘
     

更多示例:

以下示例脚本提供了更多示例:

 "scripts": {
  "r": "node echo \"Bold Text\" -s 1",
  "s": "node echo \"Light Red Text\" -f 91",
  "t": "node echo \"Light Blue Text\" -f 94",
  "u": "node echo \"Light Green Text\" -f 92",
  "v": "node echo \"Light Red Underlined Text\" -s 4 -f 91",
  "w": "node echo \"Light Red Background and White Text\" -b 101 -f 97",
  "x": "node echo \"Light Blue Background and White Text\" -b 104 -f 97",
  "y": "node echo \"Light Yellow Background and Black Text\" -f 30 -b 103",
  "z": "node echo \"Dark Gray Background and White Text\" -b 100 -f 97",
  "node-echo-all": "npm run r -s && npm run s -s && npm run t -s && npm run u -s && npm run v -s && npm run w -s && npm run x -s && npm run y -s && npm run z -s"
},
 

使用上面的脚本运行npm run node-echo-all -s将输出与上面 Bash(MacOS/Linux/etc.)部分所示的结果相同.

为简洁起见,这些脚本(以上)使用速记-s-b-f选项.但是,如果需要使它们更易于阅读,则可以分别用它们的长期等效项--set--bg-color--font-color代替.

Have recently put together a build tool with npm and package.json scripts, and I have a few echo commands to state which parts of the pipeline are currently running.

For example (from my package.json):

{
    "scripts": {
        "clean": "rimraf a-directory/",
        "preclean": "echo \"\n[ Cleaning build directories ]\n\""
    }
}

When I Bash: npm run clean it prints my echo message, and then cleans the appropriate directory.

I'd like to change colour, font weight, background text colour to make these echo statements stand out and be more informative at a glance, but I've struggled even finding a starting point that can set me off being able to do this.

There's lots of info about doing this in regular CLI/Bash scripts, via grunt and gulp, or via JS scripts, but nothing I've found is attempting it from the scripts section of package.json.

What am I missing? All help appreciated.

Many thanks.

解决方案

Consoles/terminals typically provide support for ANSI/VT100 Control sequences, so it's possible to use these codes to control font colour, font weight, background colour, etc.

  • For a Bash only solution refer to the Bash (MacOS/Linux/ etc..) section below.

  • However, if cross platform support is required then follow the solution described in the Cross Platform section below.


Bash (MacOS/Linux/ etc..)

Important Note: The following will not work successfully on non-bash consoles, such as Windows Command Prompt (i.e. cmd.exe) or PowerShell.

This example npm-script below:

"scripts": {
  "clean": "rimraf a-directory/",
  "preclean": "echo \"\\x1b[104m\\x1b[97m\n[ Cleaning build directories ]\n\\x1b[0m\""
}

...will log the something like the following in your console when running npm run clean(i.e. white text with a blue colored background):

Breakdown of the necessary syntax/codes:

            <Esc> characters
   ┌─────────┬────┴─────────┐
   │         │              │
 ┌─┴─┐     ┌─┴─┐          ┌─┴─┐
 \\x1b[104m\\x1b[97m Mssg \\x1b[0m
      └─┬─┘     └─┬┘└─┬─┘      └┬┘
        │         │   │         │
        │         │   │         │
        │         │   │         │
        │         │   │  Reset all attributes
        │         │   │
        │         │  Your Message
        │         │
        │       White Text
        │       
 Light blue background

Further examples:

The following example npm-scripts provide further examples:

"scripts": {
  "a": "echo \"\\x1b[1m\\x1b[39mBold Text\\x1b[0m\"",
  "b": "echo \"\\x1b[91mLight Red Text\\x1b[0m\"",
  "c": "echo \"\\x1b[94mLight Blue Text\\x1b[0m\"",
  "d": "echo \"\\x1b[92mLight Green Text\\x1b[0m\"",
  "e": "echo \"\\x1b[4m\\x1b[91mLight Red Underlined Text\\x1b[0m\"",
  "f": "echo \"\\x1b[101m\\x1b[97mLight Red Background and White Text\\x1b[0m\"",
  "g": "echo \"\\x1b[104m\\x1b[97mLight Blue Background and White Text\\x1b[0m\"",
  "h": "echo \"\\x1b[30m\\x1b[103mLight Yellow Background and Black Text\\x1b[0m\"",
  "i": "echo \"\\x1b[97m\\x1b[100mDark Gray Background and White Text\\x1b[0m\"",
  "bash-echo-all": "npm run a -s && npm run b -s && npm run c -s && npm run d -s && npm run e -s && npm run f -s && npm run g -s && npm run h -s && npm run i -s"
},

Running npm run bash-echo-all -s using the scripts above will output the following to your console (the -s option just makes npm log a bit less):

A more comprehensive list of codes can be found at the link provided at the top of this post, (or see codes listed in Cross Platform section below), but remember not all ANSI/VT100 Control sequences are supported.


Cross Platform

For a cross-platform solution, (one which works successfully with Bash, Windows Command Prompt / cmd.exe, and PowerShell etc..), you'll need to create a nodejs utility script to handle the logging. This nodejs script can then be invoked via your npm-scripts.

The following steps describe how this can be achieved:

  1. Create a nodejs utility script as follows:

    echo.js

    const args = process.argv;    
    const mssg = args[2];
    
    const opts = [
      '-s', '--set',
      '-b', '--bg-color',
      '-f', '--font-color'];
    
    function excapeAnsiCode(code) {
      return '\x1b[' + code + 'm';
    }
    
    const ansiStyles = opts.map(function (opt) {
      return args.indexOf(opt) > -1
          ? excapeAnsiCode(args[args.indexOf(opt) +1])
          : '';
    });
    
    console.log('%s%s%s', ansiStyles.join(''), mssg, '\x1b[0m');
    

    Let's name the file echo.js and save it in the root of your project directory, i.e. in the same folder where package.json is stored.

  2. Then, given your example, let's add a npm-script to package.json as follows:

    "scripts": {
      "clean": "rimraf a-directory/",
      "preclean": "node echo \"[ Cleaning build directories ]\" --bg-color 104 --font-color 97"
    }
    

    When running npm run clean you'll see the same message logged to your console as before when using the bash only solution, i.e. white text with a blue colored background.

Overview of usage syntax for invoking echo.js via npm-scripts

node echo \"message\" [[-s|--set] number] [[-b|--bg-color] number] [[-f|--font-color] number]

  1. node echo \"message\"

    The node echo \"message\" part is mandatory. The message is where you enter your message to be logged and it must be wrapped in escaped double quotes \"...\" to prevent splitting.

    The remaining parts, which are for the purpose of formatting/styling, are all optional and can be defined in any order. However, when used, they must proceed after the initial node echo \"message\" part, and be separated by a single space.

  2. [--set|-s]

    The --set option, or it's shorthand equivalent -s, followed by a single space, and one of the following ANSI codes can be used to specify general formatting:

    ┌─────────────────────────┐
    │ Code  Description       │
    ├─────────────────────────┤
    │  1    Bold/Bright       │
    │  2    Dim               │
    │  4    Underlined        │
    │  5    Blink             │
    │  7    Reverse/invert    │
    │  8    Hidden            │
    └─────────────────────────┘
    

    Note: Codes 1 and 4 worked successfully with Bash, however they were not supported by Windows Command Prompt and Powershell. So if repeatability is important across platforms I recommend avoiding use of the --set|-s option entirely.

  3. [--bg-color|-b]

    The --bg-color option, or it's shorthand equivalent -b, followed by a single space, and one of the following ANSI codes can be used to specify the background color:

    ┌─────────────────────────┐
    │ Code  Background Color  │
    ├─────────────────────────┤
    │  49   Default           │
    │  40   Black             │
    │  41   Red               │
    │  42   Green             │
    │  43   Yellow            │
    │  44   Blue              │
    │  45   Magenta           │
    │  46   Cyan              │
    │  47   Light Gray        │
    │  100  Dark Gray         │
    │  101  Light Red         │
    │  102  Light Green       │
    │  103  Light Yellow      │
    │  104  Light Blue        │
    │  105  Light Magenta     │
    │  106  Light Cyan        │
    │  107  White Cyan        │
    └─────────────────────────┘
    

  4. [--font-color|-f]

    The --font-color option, or it's shorthand equivalent -f, followed by a single space, and one of the following ANSI codes can be used to specify the font color:

    ┌─────────────────────────┐
    │ Code  Font Color        │
    ├─────────────────────────┤
    │  39   Default           │
    │  30   Black             │
    │  31   Red               │
    │  32   Green             │
    │  33   Yellow            │
    │  34   Blue              │
    │  35   Magenta           │
    │  36   Cyan              │
    │  37   Light Gray        │
    │  90   Dark Gray         │
    │  91   Light Red         │
    │  92   Light Green       │
    │  93   Light Yellow      │
    │  94   Light Blue        │
    │  95   Light Magenta     │
    │  96   Light Cyan        │
    │  97   White Cyan        │
    └─────────────────────────┘
    

Further examples:

The following example scripts provide further examples:

"scripts": {
  "r": "node echo \"Bold Text\" -s 1",
  "s": "node echo \"Light Red Text\" -f 91",
  "t": "node echo \"Light Blue Text\" -f 94",
  "u": "node echo \"Light Green Text\" -f 92",
  "v": "node echo \"Light Red Underlined Text\" -s 4 -f 91",
  "w": "node echo \"Light Red Background and White Text\" -b 101 -f 97",
  "x": "node echo \"Light Blue Background and White Text\" -b 104 -f 97",
  "y": "node echo \"Light Yellow Background and Black Text\" -f 30 -b 103",
  "z": "node echo \"Dark Gray Background and White Text\" -b 100 -f 97",
  "node-echo-all": "npm run r -s && npm run s -s && npm run t -s && npm run u -s && npm run v -s && npm run w -s && npm run x -s && npm run y -s && npm run z -s"
},

Running npm run node-echo-all -s using the scripts above will output the the same results as shown in the Bash (MacOS/Linux/ etc..) section above.

For brevity these scripts (above) utilize the shorthand -s, -b, and -f options. However they can be substituted with their longhand equivalents --set, --bg-color, and --font-color respectively if necessary to make your code more human readable.

这篇关于通过package.json将视觉样式应用于npm脚本中使用的echo命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆