Use Vite env variables inside Node scripts and test runners via a require hook.
npm install --save-dev vite-register
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 tofalse
) - 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
- from a
- Support
<UserConfig>.envPrefix
(defaults toVITE_
) - Support
<UserConfig>.envDir
(defaults to project root)
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
Can be combined with esbuild-runner for TypeScript/JSX/ESM support.
mocha -r esbuild-runner/register -r vite-register [pattern]
↪️ lukeed/uvu
Can be combined with tsm or esbuild-runner for TypeScript/JSX/ESM support.
uvu -r tsm -r vite-register [pattern]
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.
Jest currently doesn't support hooks (facebook/jest#11295). If you need Jest unique features, you're better off switching to Vitest.
MIT