Dark Mode

Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 01a9a58

Browse files
authored
fix(browser): fix import.meta.env define (#9205)
1 parent 01c5645 commit 01a9a58

File tree

4 files changed

+21
-1
lines changed
  • packages/browser/src
    • client/tester
      • tester.ts
    • node
      • plugin.ts
  • test/browser
    • test
      • env.test.ts
    • vitest.config.mts

4 files changed

+21
-1
lines changed

packages/browser/src/client/tester/tester.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@ async function prepareTestEnvironment(options: PrepareOptions) {
101101

102102
const state = getWorkerState()
103103

104-
state.metaEnv = import.meta.env
104+
// @ts-expect-error replaced with `import.meta.env` by transform
105+
state.metaEnv = __vitest_browser_import_meta_env_init__
105106
state.onCancel = onCancel
106107
state.ctx.rpc = rpc as any
107108
state.rpc = rpc as any

packages/browser/src/node/plugin.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -622,6 +622,18 @@ body {
622622
}
623623
},
624624
},
625+
{
626+
name: 'vitest:browser:__vitest_browser_import_meta_env_init__',
627+
transform: {
628+
handler(code) {
629+
// this transform runs after `vitest:meta-env-replacer` so that
630+
// `import.meta.env` will be handled by Vite import analysis to match behavior.
631+
if (code.includes('__vitest_browser_import_meta_env_init__')) {
632+
return code.replace('__vitest_browser_import_meta_env_init__', 'import.meta.env')
633+
}
634+
},
635+
},
636+
},
625637
]
626638
}
627639

test/browser/test/env.test.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ test('custom env', () => {
1919
expect(import.meta.env.CUSTOM_ENV).toBe('foo')
2020
})
2121

22+
test('import.meta.env via define', () => {
23+
expect(import.meta.env.DEFINE_CUSTOM_ENV).toBe('define-custom-env')
24+
})
25+
2226
test('ignores import.meta.env in string literals', () => {
2327
expect('import.meta.env').toBe('import' + '.meta.env')
2428
})

test/browser/vitest.config.mts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ export default defineConfig({
5252
optimizeDeps: {
5353
include: ['@vitest/cjs-lib', '@vitest/bundled-lib', 'react/jsx-dev-runtime'],
5454
},
55+
define: {
56+
'import.meta.env.DEFINE_CUSTOM_ENV': JSON.stringify('define-custom-env'),
57+
},
5558
test: {
5659
include: ['test/**.test.{ts,js,tsx}'],
5760
includeSource: ['src/*.ts'],

0 commit comments

Comments
(0)