Skip to content

Commit

Permalink
feat: allow changing import.meta.env (#714)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Feb 9, 2022
1 parent d02db1b commit 5f00788
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 0 deletions.
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
// 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

0 comments on commit 5f00788

Please sign in to comment.