vitest: `.env` files are not loaded
Describe the bug
There’s an envDir
section in Vite docs https://vitejs.dev/config/#envdir saying that .env
files are loaded from root
dir by default.
But neither .env
nor .env.test
file is loaded in vitest 0.9.3
Reproduction
https://github.com/meoyawn/vitest-env
System Info
System:
OS: macOS 11.6.2
CPU: (8) x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
Memory: 2.65 GB / 16.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 17.9.0 - /usr/local/bin/node
Yarn: 1.22.18 - /usr/local/bin/yarn
npm: 8.5.5 - /usr/local/bin/npm
Browsers:
Brave Browser: 98.1.35.101
Chrome: 100.0.4896.88
Firefox: 92.0
Safari: 15.2
npmPackages:
vitest: ^0.9.3 => 0.9.3
Used Package Manager
yarn
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that reports the same bug to avoid creating a duplicate.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 15 (5 by maintainers)
If I understand the problem correctly, then vitest already has a solution for this: https://vitest.dev/config/#setupfiles
I simply had to add the line
setupFiles: 'dotenv/config',
to my vitest.config.ts file (as I already had dotenv installed as dev dependency), and that took care of loading my .env file.Example repo: https://github.com/repetitioestmaterstudiorum/ts-boiler/blob/master/vitest.config.ts
@sheremet-va it works! Thank you so much
Yes, Vite exposes only env variables starting with
VITE_
. Vite also exposesloadEnv
function that returns a env object (that you can assign toprocess.env
likeObject.assign(procces.env, loadEnv(mode, './', ''))
), you can use it and pass an empty prefix.I have just this minute hit the exact same issue. I have a Vue 3 application built with Vite and tested with Vitest. I created a
.env
file to move some of the variables into environment variables. So, using an example in the docs, I change my root vue component to get its title fromimport.meta.env.VITE_APP_TITLE
and it works fine. However, when the tests run, this is completely blank/undefined. Is there something special I need to do with the vitest config? This seems to defeat the premise that vitest will use the same config as vite.https://github.com/vitest-dev/vitest/discussions/1149