Skip to content

Commit

Permalink
fix(env-replacer): don't modify string literals (#1943)
Browse files Browse the repository at this point in the history
* fix(env-replacer): don't modify string literals

fix #1941

* test(env-replacer): verify string literals are ignored

* chore: fix typo envRelacer.ts -> envReplacer.ts

* chore: fix typo envRelacer.ts -> envReplacer.ts

* chore: move strip-literal to correct package
  • Loading branch information
tony19 committed Sep 1, 2022
1 parent 35bb461 commit 5182489
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 4 deletions.
1 change: 1 addition & 0 deletions packages/vitest/package.json
Expand Up @@ -98,6 +98,7 @@
"chai": "^4.3.6",
"debug": "^4.3.4",
"local-pkg": "^0.4.2",
"strip-literal": "^0.4.0",
"tinypool": "^0.2.4",
"tinyspy": "^1.0.2",
"vite": "^2.9.12 || ^3.0.0-0"
Expand Down
@@ -1,5 +1,6 @@
import MagicString from 'magic-string'
import type { Plugin } from 'vite'
import { stripLiteral } from 'strip-literal'

// so people can reassign envs at runtime
// import.meta.env.VITE_NAME = 'app' -> process.env.VITE_NAME = 'app'
Expand All @@ -8,9 +9,11 @@ export const EnvReplacerPlugin = (): Plugin => {
name: 'vitest:env-replacer',
enforce: 'pre',
transform(code) {
let s: MagicString | null = null
if (!/\bimport\.meta\.env\b/g.test(code))
return null

const envs = code.matchAll(/\bimport\.meta\.env\b/g)
let s: MagicString | null = null
const envs = stripLiteral(code).matchAll(/\bimport\.meta\.env\b/g)

for (const env of envs) {
s ||= new MagicString(code)
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/plugins/index.ts
Expand Up @@ -4,7 +4,7 @@ import type { ResolvedConfig, UserConfig } from '../../types'
import { deepMerge, ensurePackageInstalled, notNullish } from '../../utils'
import { resolveApiConfig } from '../config'
import { Vitest } from '../core'
import { EnvReplacerPlugin } from './envRelacer'
import { EnvReplacerPlugin } from './envReplacer'
import { GlobalSetupPlugin } from './globalSetup'
import { MocksPlugin } from './mock'
import { CSSEnablerPlugin } from './cssEnabler'
Expand Down
4 changes: 3 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions test/core/test/env.test.ts
Expand Up @@ -43,3 +43,7 @@ test('custom env', () => {
expect(process.env.CUSTOM_ENV).toBe('foo')
expect(import.meta.env.CUSTOM_ENV).toBe('foo')
})

test('ignores import.meta.env in string literals', () => {
expect('import.meta.env').toBe('import' + '.meta.env')
})

0 comments on commit 5182489

Please sign in to comment.