Setting up env variable in npm script is an easy way to run scripts with the proper env variable setup. This pattern allow us to abstract sensitive information from code and provide customization based on the individual needs.
A classical pattern use in npm script will look like this
"scripts": {
"test": "TOKEN=debugToken jest"
}
This pattern soon hit into an inevitable issue when our application size grew or the increase use of env variable as configurations for our application.
"scripts": {
"test": "TOKEN=debugToken DDB_TABLE_NAME_1=ddbtablename_1 DDB_TABLE_NAME_2=ddbtablename_2 DDB_TABLE_NAME_3=ddbtablename_3 jest"
}
One alternative will be to shift the declaration of env variable to a shell script and take advantage of npm config as the source of truth
"config": {
"api_gateway_url": "https://<URL>/Prod/webhook/",
"telegram_token": "<TELEGRAM_TOKEN>",
"ddb_table_name_for_user_subscription": "telegram-bot-user-subscription",
"ddb_table_name_for_dialog_state": "telegram-bot-dialog_state",
"ntba_fix_319": 1
},
"scripts": {
"test": "./setup-env.sh 'jest'"
}
in our ./setup-env.sh, we can refer the config env with a prefix “npm_package_config”
DDB_TABLE_NAME_FOR_USER_SUBSCRIPTION="$npm_package_config_ddb_table_name_for_user_subscription" \
DDB_TABLE_NAME_FOR_DIALOG_STATE="$npm_package_config_ddb_table_name_for_dialog_state" \
NTBA_FIX_319=$npm_package_config_ntba_fix_319 \
TELEGRAM_TOKEN=$npm_package_config_telegram_token \
$1