Using .env Variables in package.json Scripts
Ever run into a CLI that requires you to pass values that you already have stored in your .env file?
I'm embarrassed to say I've written a script in the past that just was a wrapper around a CLI command just so I could call require('dotenv').config()
before it. 😶
There's a better way though. Let's look at this Supabase command for generating TypeScript types from your database schema:
supabase gen types typescript --project-id PROJECT_ID_HERE > database.types.ts
I have the value for PROJECT_ID_HERE in my .env
set as SUPABASE_REFERENCE_ID
.
Fortunately, there is a package that can help us apply our .env
and execute commands after the environment variables have been applied: env-cmd.
The important flag that we need to use is -x
here, as this does the following:
Replace $var in args and command with environment variables
So our command, rewritten to use env-cmd would look like this in our package.json script:
"generate:db:types": "env-cmd -x supabase gen types typescript --project-id $SUPABASE_REFERENCE_ID > database.types.ts"