How to display color in yarn script command? - yarnpkg

Yarn seems to not parse the color codes I pass via echo:
package.json:
"a": "echo \"\\x1b[1m\\x1b[39mBold Text\\x1b[0m\"",
result:
$ yarn a
\x1b[1m\x1b[39mBold Text\x1b[0m

Related

Change value of shell variables as an argument of npm run command

I am trying to accomplish the following -> Right now I use cypress to run e2e tests. It is being launched by npm command. I have several environments and different user permission. I created a shell script, where I have stored value of environment and user permission rights. What I want to do is to have opportunity to run npm command with parameters to change the value of variable from shell script. Could someone give a clue, is it even possible? The expected behaviour is to write something like:
npm run cy dev3,full
And have the opportunity to change the value of shell script variable to launch necessary environament and change value of user permissions.
package.json command:
"scripts": {
"cy": "./scripts/cypress.sh",
}
cypress.sh file content
#!/usr/bin/env bash
DEV_ENV="${DEV_ENV:-"dev3"}"
USER_TYPE="${USER_TYPE:-"full"}"
COMMAND="cypress open \
--browser chrome \
--config baseUrl=https://environment-$DEV_ENV.com \
--env DEV_ENV=https://environment-$DEV_ENV.com,USER_TYPE=$USER_TYPE
"
eval $COMMAND
Are you trying to change the environment variables seen in cypress.sh? If so, you can just execute npm run like this:
DEV_ENV=dev2 USER_TYPE=empty npm run cy
and it will change the value of DEV_ENV and USER_TYPE.
If you want to strictly run it by using the format you gave (npm run cy dev3,full), the args dev3,full are passed on to cypress.sh, so you can just parse the arguments directly in cypress.sh:
if [ ! -z "$1" ]; then
# do whatever here...
fi

Pass environment variable from command line to yarn

I have a code that reads port number from environment variable or from config. Code looks like this
const port = process.env.PORT || serverConfig.port;
await app.listen(port);
To run app without defining environment variable, I run following yarn command.
yarn start:dev
This command works successfully in Linux shell and Windows command line.
Now, I want to pass environment variable. I tried following,
PORT=2344 yarn start:dev
This commands works successfully in Linux shell but failing in Windows command line. I tried following ways but couldn't get it to work.
Tried: PORT=2344 yarn start:dev
I got error: 'PORT' is not recognized as an internal or external command,
operable program or batch file.
Tried: yarn PORT=2344 start:dev
I got error: yarn run v1.17.3
error Command "PORT=2344" not found.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Any idea please? I know, I can define environment variables from System Properties in Windows. But any way if I can do it from command line?
i'd suggest you use the NPM module called cross-env. it allows adding particular env variables on the command line regardless of platform. with that said, you may try:
$ cross-env PORT=2344 yarn start:dev
You can chain commands on the Windows command prompt with &(or &&). To set an environment variable you need to use the set command.
The result should look like this: set PORT=1234 && yarn start:dev.
Found a solution for this problem in Windows command prompt.
Create a .env file in project root folder (outside src folder).
Define PORT in it. In my case, contents of .env file will be,
PORT=2344
Run yarn start:dev
Application will use port number that you have specified in .env file.
Put .env file at root. Then following command will expose content of .env file and then run yarn start command
$ source .env && yarn start
or this command
$ export $(cat .env) && yarn start
If update any variable in .env then close the terminal and open new terminal window and can again run above command. Or else can also run unset command to remove existing var.
unset VAR_NAME
You can use popular package dotenv:
create a file .env in root directory
put all your env vars
e.g.:
ENV=DEVELOPMENT
run your code like this
$ node -r dotenv/config your_script.js
here the explanation:
[https://github.com/motdotla/dotenv#preload]
To define environment variables in the Windows command prompt we can use the set command, you can then split your call into two lines.
set PORT=2344
yarn start:dev
The set command persists within the current command prompt, so you only need to run it once.
The equivalent command in bash is 'export'.
FYI (not a direct answer). I was attempting this in VS Code - passing .env variables through yarn to a JavaScript app. Google had very few examples so I'm sharing this for posterity as it's somewhat related.
The following simply substitutes text normally placed directly into the package.json or script file. Use this to quickly obfuscate or externalize your delivery configurations.
In Environment Variable File (.env)
PORT=2344
In Yarn File (package.json)
source .env; yarn ./start.sh --port $PORT
In Yarn Script (start.sh)
#!/bin/bash
while [ $? != 0 ]; do
node dist/src/index.js $1; #replace with your app call#
done
The app then accepts port as a variable. Great for multi-tenant deployments.

How to define an environment variable that can be automatically used in multiple npm scripts?

Consider the following npm scripts.
$ npm run
available via `npm run-script`:
make
OUTPUT=dist/main.js bash -c 'elm make src/Main.js --output=$0 $1'
make:dev
npm run make -- '$OUTPUT' --debug
make:prod
npm run make -- '>(npm run uglify -- $OUTPUT)' --optimize
uglify
uglifyjs --compress 'pure_funcs="F2,F3,F4,F5,F6,F7,F8,F9,A2,A3,A4,A5,A6,A7,A8,A9",pure_getters,keep_fargs=false,unsafe_comps,unsafe' | uglifyjs --mangle --output=
I'd like to use it as follows:
$ npm run make -- '$OUTPUT' '--debug'
> experiment#0.1.0 experiment /Users/Adit/experiment
> OUTPUT=dist/main.js bash -c 'elm make src/Main.js --output=$0 $1' '$OUTPUT' '--debug'
This would correctly create the debug build of the Elm application. However, this is not what happens. Instead of using single quotes, npm run uses double quotes:
$ npm run make -- '$OUTPUT' '--debug'
> experiment#0.1.0 experiment /Users/Adit/experiment
> OUTPUT=dist/main.js bash -c 'elm make src/Main.js --output=$0 $1' "$OUTPUT" "--debug"
Due to this the output is not what I expect it to be. What's the best way to resolve this issue without writing a custom shell script? I want to use the OUTPUT variable in two different commands. However, I only want to define it in one place.
I solved the problem as follows.
{
"config": {
"input": "src/Main.elm",
"output": "dist/main.js"
},
"scripts": {
"make": "elm make $npm_package_config_input --output $npm_package_config_output",
"make:dev": "npm run make -- --debug",
"make:prod": "npm run make -- --optimize",
"postmake:prod": "uglifyjs $npm_package_config_output --compress 'pure_funcs=\"F2,F3,F4,F5,F6,F7,F8,F9,A2,A3,A4,A5,A6,A7,A8,A9\",pure_getters,keep_fargs=false,unsafe_comps,unsafe' | uglifyjs --mangle --output=$npm_package_config_output"
}
}
Hence, if you have a configuration variables that you'd like to use in multiple npm scripts, you can add them to the config dictionary of package.json. After that, you can access them as environment variables in the npm scripts via the name $npm_package_config_<name> where <name> is the name of your config variable.
I also used a post script instead of process substitution to uglify the output of the Elm compiler. Doing so was overall less of a hassle than using process substitution via bash -c.
Finally, you can run make, make:dev, or make:prod for different builds. The first one is a regular build. The second one is a development build with the Elm debugging tools. The third one is a regular build which is optimized and minified for production use.

yarn run script with parameters

How do I pass a parameter? When I run "yarn generate" it will make both a "-p" and a "test" directory. But it works well when I run "mkdir -p test" in bash. I tried to [-p] as well but it only creates that directory.
"scripts": {
"generate": "mkdir -p test"
}
Although I could not reproduce the issue that you mentioned (my config: node v8.11.1 and yarn v1.2.1, latest MacOS), according to the yarn docs, you can pass the arguments to yarn script by appending them normally, like so:
yarn generate -p test
In this case your npm (yarn) scripts config (in the package.json, I assume) would look like
"scripts": {
"generate": "mkdir"
}
If you're using Windows, you indeed won't have the mkdir -p flag (read this). In order to make what you want (check if the folder does not exist and if so, create one) you'd need to use some cmd commands. So your package.json will contain smth like
"scripts": {
"generate": "IF NOT EXIST test mkdir test"
}

How to set shell for npm run-scripts in Windows

I'm running npm on Windows and would like to use & style parallel operations in run-scripts
but running in parallel in cmd is kind of messy
in my package.json file I'd like to write-
scripts: { "go": "cmd1 & cmd2"}
but npm executes the script under cmd.exe which does not know about ; I could change this to
scripts: { "go": "bats/bat1.bat") where bat1.bat is a cmd bat file that uses the windows style call or start commands to run commands in parallel. which works but gives me a script that only works on Windows.
It would be a lot simpler if I could get npm to run the script under a bash clone or cygwin.
I tried
config: { "shell": "bash"}
but that still ran cmd.exe
Is there any way to tell npm to run-scripts using a specific shell (not cmd.exe)?
Since npm 5.1
npm config set script-shell "C:\\Program Files (x86)\\git\\bin\\bash.exe"
or (64bit installation)
npm config set script-shell "C:\\Program Files\\git\\bin\\bash.exe"
Note that you need to have git for windows installed.
You can revert it by running:
npm config delete script-shell
Here's one way to do it:
Create a script, such as my_script.sh, in your project bin directory.
In your package.json file, add a line to run the script using bash. For example:
"scripts": {
"boogie": "bash bin/my_script.sh"
}
Now you can run your bash script from npm by:
npm run-script boogie
Not very elegant, but it works.
If you are developing in both Windows and Linux/Unix, then at least this approach is fairly portable to both environments.
Ideally, overriding the npm shell config parameter should work, but npm (at least version 1.4.14) seems in Windows to ignore the setting and use cmd.exe instead.
Use the following command in your bash or Git Bash shell to find out the shell setting:
$ npm config ls -l | grep shell
By default, the output will be:
shell = "C:\\WINDOWS\\system32\\cmd.exe"
However, to override the default shell parameter, you can add (or edit) an npmrc file to the \Users\yourusername\AppData\Roaming\npm\etc directory. Just add the following line:
shell = "C:\\Program Files (x86)\\git\\bin\\bash.exe"
The path you use can be any valid path to bash.exe. Now, if you run the above "npm config ls -l | grep shell" command, you will see the following output, indicating that the shell parameter has been overriden:
shell = "C:\\Program Files (x86)\\git\\bin\\bash.exe"
; shell = "C:\\WINDOWS\\system32\\cmd.exe" (overridden)
One day, perhaps, a new version of npm will pay attention to the overridden shell parameter.
You can also use cross-platform powershell https://github.com/powershell/powershell#get-powershell for npm scripts.
To set for single project, run this from project root folder:
npm config set script-shell pwsh --userconfig ./.npmrc
To globally set for all node projects:
npm config set script-shell pwsh [--global]
just using CMD's way to run .bat!
.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"app": "cd build & browser-sync start --server --files 'index.html'",
"bat": "start start-browser.bat",
"starts": "start http://localhost:7777/datas/ && start http://localhost:7777/Info/"
},
.bat
start http://localhost:7777/datas/ && start http://localhost:7777/Info/
Use a specifically created node_module for this purpose. I suggest using npm-run-all, but others exists, such as parallelshell.
Parallelshell example is below for drop-in-replacement for your question.
"scripts": {
"parallelexample1": "parallelshell \"echo 1\" \"echo 2\" \"echo 3\""
},
following command:
npm run parallelexample1
works both on windows and unix(Linux/MacOS).
Interestingly npm-run-all does not support shell commands; therefore we need to put all shell commands to separate scripts like below.
"scripts": {
"parallelexample2": "npm-run-all echo*",
"echo1": "echo 1",
"echo2": "echo 2",
"echo3": "echo 3"
},
Following command:
npm run parallelexample2
works both on windows and unix(Linux/MacOS).
In my case I just needed to run npm start from inside Bash. I run cmd then I open bash by running "c:\Program Files\Git\bin\bash.exe". Under bash shell I then was able to call npm build and npm start succesfully.
You may already have bash if you are using Git. If not, you can install it.
Hope this may save someone's time.

Resources