node.jswindowsnpmpackage.jsonnpm-scripts

Mixing concurrently and cross-env in a package.json script


Building a monorepo template, I'm facing an issue in the scripts of my package.json. I'm trying to make my scripts compatible with npm alternatives like yarn or pnpm. So I tried to use a config object to specify the wanted CLI:

{
  "config": {
    "cli": "npm"
  }
}

Then I was able to access the value through the environment variable npm_package_config_cli. Since the usage of environment variables has different syntaxes between unix systems and windows, I used cross-env. This worked well for most of my scripts, for example:

"dev-front": "cross-env-shell \"cd ./frontend && $npm_package_config_cli run dev\"",

Here you can see the usage of cross-env-shell to execute the command between quotes:

cd ./frontend && $npm_package_config_cli run dev

With $npm_package_config_cli being resolved by cross-env according to the OS.

My package.json purpose is to drive the scripts in frontend and backend folders of my monorepo template. So I'm using concurrently to keep track of the different outputs. My issue is when using cross-env-shell along with concurrently. I tried to call cross-env-shell "inside" concurrently and vice-versa, with single and/or double quotes, but $npm_package_config_cli is not resolved on windows.

A minimal package.json with the failing dev script (dev-front and dev-back are working):

{
  "config": {
    "cli": "npm"
  },
  "scripts": {
    "dev": "concurrently -n front,back -c green,yellow -t 'HH:mm:ss' -p '{name} {time}' 'cross-env-shell \"cd ./frontend && $npm_package_config_cli run dev\"' 'cross-env-shell \"cd ./backend && $npm_package_config_cli run dev\"'"
    "dev-front": "cross-env-shell \"cd ./frontend && $npm_package_config_cli run dev\"",
    "dev-back": "cross-env-shell \"cd ./backend && $npm_package_config_cli run dev\""
  },
  "devDependencies": {
    "concurrently": "^7.6.0",
    "cross-env": "^7.0.3"
  }
}

Any hint on the valid syntax? Is there a better approach?


Solution

  • Trying harder, the following combination worked with concurrently wildcards:

    {
      "config": {
        "cli": "npm"
      },
      "scripts": {
        "dev": "cross-env-shell 'concurrently -c green,yellow -t \"HH:mm:ss\" -p \"{name} {time}\" \"$npm_package_config_cli:dev-*\"'",
        "dev-front": "cross-env-shell \"cd ./frontend && $npm_package_config_cli run dev\"",
        "dev-back": "cross-env-shell \"cd ./backend && $npm_package_config_cli run dev\""
      },
      "devDependencies": {
        "concurrently": "^7.6.0",
        "cross-env": "^7.0.3"
      }
    }