fix(browser): fix import.meta.env define (#9205)

This commit is contained in:
Hiroshi Ogawa 2025-12-08 17:54:31 +09:00 committed by GitHub
parent 01c56454d2
commit 01a9a58d90
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 21 additions and 1 deletions

View File

@ -101,7 +101,8 @@ async function prepareTestEnvironment(options: PrepareOptions) {
const state = getWorkerState()
state.metaEnv = import.meta.env
// @ts-expect-error replaced with `import.meta.env` by transform
state.metaEnv = __vitest_browser_import_meta_env_init__
state.onCancel = onCancel
state.ctx.rpc = rpc as any
state.rpc = rpc as any

View File

@ -622,6 +622,18 @@ body {
}
},
},
{
name: 'vitest:browser:__vitest_browser_import_meta_env_init__',
transform: {
handler(code) {
// this transform runs after `vitest:meta-env-replacer` so that
// `import.meta.env` will be handled by Vite import analysis to match behavior.
if (code.includes('__vitest_browser_import_meta_env_init__')) {
return code.replace('__vitest_browser_import_meta_env_init__', 'import.meta.env')
}
},
},
},
]
}

View File

@ -19,6 +19,10 @@ test('custom env', () => {
expect(import.meta.env.CUSTOM_ENV).toBe('foo')
})
test('import.meta.env via define', () => {
expect(import.meta.env.DEFINE_CUSTOM_ENV).toBe('define-custom-env')
})
test('ignores import.meta.env in string literals', () => {
expect('import.meta.env').toBe('import' + '.meta.env')
})

View File

@ -52,6 +52,9 @@ export default defineConfig({
optimizeDeps: {
include: ['@vitest/cjs-lib', '@vitest/bundled-lib', 'react/jsx-dev-runtime'],
},
define: {
'import.meta.env.DEFINE_CUSTOM_ENV': JSON.stringify('define-custom-env'),
},
test: {
include: ['test/**.test.{ts,js,tsx}'],
includeSource: ['src/*.ts'],