Skip to content

Use Vite env variables inside Node scripts and test runners via a require hook.

License

Notifications You must be signed in to change notification settings

tommywalkie/vite-register

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

vite-register

Use Vite env variables inside Node scripts and test runners via a require hook.


Install

npm install --save-dev vite-register

Features

Pretty much like Vite does, vite-register will statically replace variables.

  • Support import.meta.env.MODE
  • Support import.meta.env.DEV
  • Support import.meta.env.PROD
  • Support import.meta.env.SSR (defaults to false)
  • Support import.meta.env.BASE_URL
  • Support loading variables
    • from a .env file
    • from a .env.local file
    • from a .env.[mode] file
    • from a .env.[mode].local file
  • Support <UserConfig>.envPrefix (defaults to VITE_)
  • Support <UserConfig>.envDir (defaults to project root)

Usage

This hook can be used with the Node CLI and some test runners supporting hooks via the -r (--require) option.

# Assuming envPrefix => 'VITE_'
echo 'VITE_FOO="hello world"' > .env
echo 'console.log(import.meta.env.VITE_FOO);' > index.js
node -r vite-register index.js
> hello world

vite-register can look into Vite configuration files (vite.config.[ext]) and retrieve base and mode.

In most cases, TypeScript/JSX/ESM support in configuration files and scripts can be provided by third-party hooks like tsm, esbuild-runner or esbuild-register, before vite-register hook.

node -r esbuild-runner/register -r vite-register index.ts

Mocha

↪️ mochajs/mocha

Can be combined with esbuild-runner for TypeScript/JSX/ESM support.

mocha -r esbuild-runner/register -r vite-register [pattern]

uvu

↪️ lukeed/uvu

Can be combined with tsm or esbuild-runner for TypeScript/JSX/ESM support.

uvu -r tsm -r vite-register [pattern]

FAQ

When should I use vite-register over Vitest, or vice-versa ?

  • If you want a test framework, use Vitest.
  • If you need Jest features (snapshot, mocking, etc.), use Vitest.
  • If package size really matters, use vite-register.
  • If you want something actively maintained by Vite members, use Vitest.
  • If migrating tests becomes an issue, use vite-register.
  • If you really can't upgrade to Node >=v14, use vite-register.

Support Jest ?

Jest currently doesn't support hooks (facebook/jest#11295). If you need Jest unique features, you're better off switching to Vitest.

License

MIT

About

Use Vite env variables inside Node scripts and test runners via a require hook.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published