Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow changing import.meta.env #714

Merged
merged 6 commits into from Feb 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions packages/vitest/src/node/plugins/envReplacer.ts
@@ -0,0 +1,30 @@
import MagicString from 'magic-string'
import type { Plugin } from 'vite'

export const EnvReplacerPlugin = (): Plugin => {
return {
name: 'vitest:env-replacer',
enforce: 'pre',
transform(code) {
let s: MagicString | null = null

const envs = code.matchAll(/\bimport\.meta\.env\b/g)

for (const env of envs) {
s ||= new MagicString(code)

const startIndex = env.index!
const endIndex = startIndex + env[0].length

s.overwrite(startIndex, endIndex, 'process.env')
}

if (s) {
return {
code: s.toString(),
map: s.generateMap({ hires: true }),
}
}
},
}
}
19 changes: 19 additions & 0 deletions packages/vitest/src/node/plugins/index.ts
Expand Up @@ -6,6 +6,7 @@ import { resolveApiConfig } from '../config'
import { Vitest } from '../core'
import { GlobalSetupPlugin } from './globalSetup'
import { MocksPlugin } from './mock'
import { EnvReplacerPlugin } from './envReplacer'

export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest()): Promise<VitePlugin[]> {
let haveStarted = false
Expand Down Expand Up @@ -57,6 +58,23 @@ export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest())
)
options.api = resolveApiConfig(options)
options.watch = options.watch && !options.run

process.env.BASE_URL ??= viteConfig.base
process.env.MODE ??= viteConfig.mode
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not so sure about the MODE convention here, it feels too general to me. Do we have any references for other tools using it? or we better use VITEST_MODE or VITE_MODE

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what Vite uses on import.meta.env

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All these variables are default values on import.meta.env that always exist

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And we are allowing people to reassign them by making import.meta.env = process.env

we can assign them to process.metaEnv if you don't want to collaps with other tools, but I know this approach is wildly used now to support testing Vite in jest (using process.env that is)

process.metaEnv can even allow booleans

we can hide implementation on some helper like vi.mockEnv(env, value), but people may get confused when process.env will stay the same

// process.env can have only string values and will cast string on it if we pass other type,
// so we are making them truthy
process.env.PROD ??= viteConfig.env.PROD ? '1' : ''
process.env.DEV ??= viteConfig.env.DEV ? '1' : ''
process.env.SSR ??= '1'

// account for user env defines
for (const key in viteConfig.define) {
if (key.startsWith('import.meta.env.')) {
const val = viteConfig.define[key]
const envKey = key.slice('import.meta.env.'.length)
process.env[envKey] = typeof val === 'string' ? JSON.parse(val) : val
}
}
},
async configureServer(server) {
if (haveStarted)
Expand All @@ -71,6 +89,7 @@ export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest())
await server.watcher.close()
},
},
EnvReplacerPlugin(),
MocksPlugin(),
GlobalSetupPlugin(ctx),
options.ui
Expand Down
3 changes: 3 additions & 0 deletions test/core/src/env.ts
@@ -0,0 +1,3 @@
export function getAuthToken() {
return import.meta.env.AUTH_TOKEN
}
19 changes: 19 additions & 0 deletions test/core/test/env.test.ts
@@ -0,0 +1,19 @@
import { expect, test } from 'vitest'
import { getAuthToken } from '../src/env'

test('can reassign env locally', () => {
import.meta.env.VITEST_ENV = 'TEST'
expect(import.meta.env.VITEST_ENV).toBe('TEST')
})

test('can reassign env everywhere', () => {
import.meta.env.AUTH_TOKEN = '123'
expect(getAuthToken()).toBe('123')
process.env.AUTH_TOKEN = '321'
expect(getAuthToken()).toBe('321')
})

test('can see env in "define"', () => {
expect(import.meta.env.TEST_NAME).toBe('hello world')
expect(process.env.TEST_NAME).toBe('hello world')
})
12 changes: 12 additions & 0 deletions test/core/types/env.d.ts
@@ -0,0 +1,12 @@
interface ImportMeta {
readonly env: ImportMetaEnv
}

interface ImportMetaEnv {
[key: string]: string | boolean | undefined
BASE_URL: string
MODE: string
DEV: boolean
PROD: boolean
SSR: boolean
}
3 changes: 3 additions & 0 deletions test/core/vitest.config.ts
Expand Up @@ -17,6 +17,9 @@ export default defineConfig({
},
},
],
define: {
'import.meta.env.TEST_NAME': '"hello world"',
},
test: {
testTimeout: 2000,
// threads: false,
Expand Down