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

fix(env-replacer): don't modify string literals #1943

Merged
merged 5 commits into from Sep 1, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
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')
})