Seeding with Drizzle ORM and tsx runner
I'm trying to seed my database. My project uses Drizzle ORM, and I have a seed.ts in my db directory. Simply including a
tsx seed.ts
gives me a message that my environment is not set up.
It's my first full stack project. I need some help pointing in the right direction for convincing the environment to be set up in the same way as running for a dev/test/prod db, but for the script that tsx will run.Solution:Jump to solution
Install the
tsx
runner. If you are using Node.js 20 or later, the following package.json entry will run your script:
...4 Replies
Running standalone
.ts
can be unexpectedly difficult. I've had great success with tsno
(https://github.com/egoist/tsno) but I'm not sure if its the preferred method anymore. Hasnt needed any extra configuration other than proper imports inside the standalone .ts
fileGitHub
GitHub - egoist/tsno:
node
with typescript support, importing fro...node
with typescript support, importing from URL, etc. - GitHub - egoist/tsno: node
with typescript support, importing from URL, etc.Also, if you happen to have bun that might be worth a shot too
for seed scripts and such, bun is my recommendation
the reason you're environment isn't seen is because node doesn't inheritly load your .env file, so you'll need to use something like
dotenv
in your seed script to load them
make sure that your env variables are loaded before you try to connect to the db
good debugging tip is to console log the connection keys right before you create your drizzle connection. if they are undefined, you know that they failed to get loaded in for whatever reason
use wslSolution
Install the
tsx
runner. If you are using Node.js 20 or later, the following package.json entry will run your script:
If you're using Node.js before 20, use this instead:
Your script will look similar to this:
If you're using Node.js < 20, at the top, also insert this before the db import: