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 4 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 @@ -5,6 +5,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 @@ -47,6 +48,23 @@ export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest())
// viteConfig.test is final now, merge it for real
options = deepMerge(options, viteConfig.test as any || {})
options.api = resolveApiConfig(options)

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'
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved

// 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 @@ -61,6 +79,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