DEV Community

t-o-d
t-o-d

Posted on

Tips for writing npm-scripts in npm-run-all for different purposes.

  • The npm-scripts are used in package.json for task processing in web development.
  • We also use npm-run-all, which is useful for serialization and parallelization of multiple processes.
  • Therefore, we'll use it to illustrate a small technique to make npm-scripts flexible and clear.

Result

  • A description of the results is given first.
  • The following package.json is a task to mainly build and watch.
{
  "scripts": {
    "build"      : "run-s build:{sass,ts}",
    "build:sass" : "sass input.scss output.css",
    "build:ts"   : "tsc main.ts",
    "watch"      : "run-s watch:{sass,ts}",
    "watch:sass" : "sass --watch input.scss output.css",
    "watch:ts"   : "tsc -w main.ts"
  }
}

Description

  • The method used here is to specify what to do with the process in braces.

Specification using braces

  • There are three ways to execute a task classified by group in a colon (:) in a single session.
    • build-basic
    • build-glob
    • build-brace
{
  "scripts": {
    "build-basic" : "run-s build:sass build:ts",
    "build-glob"  : "run-s build:*",
    "build-brace" : "run-s build:{sass,ts}",
    "build:sass"  : "sass input.scss output.css",
    "build:ts"    : "tsc main.ts",
  }
}
  • From these I use the method specified in braces, such as build-brace.
  • The benefits are as follows.
    • unduplicated
      • There is no duplication of tasks like run-s build:sass build:ts, and if the number of tasks increases in the future, you only need to describe the purpose of the task.
    • clarification
      • Compared to an asterisk specification such as run-s build:*, the explicit description makes the process easier to understand.
    • ordering
      • The processes are performed in the order of the braces, so even if you reverse build:sass and build:ts in package.json, there is no problem.
        • If you use run-s build:*, the order of processing is the same as the order in package.json, which may cause a problem if you use it in reverse.

Conclusion

  • The above reminded us of the importance of readability, clarity, and non-overlap in the task as well.

Link

Top comments (0)